Given the root of a binary tree, return the sum of all left leaves.
A leaf is a node with no children. A left leaf is a leaf that is the left child of its parent.
Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.
0
.[1, 1000]
.-1000 <= Node.val <= 1000
.To solve this problem, we can perform a traversal of the binary tree (using DFS or BFS) and check each node to see if it is a left leaf. If a node is determined to be a left leaf, we add its value to a running sum.
0
.# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
def is_leaf(node):
return node is not None and node.left is None and node.right is None
def dfs(node, is_left):
if node is None:
return 0
if is_leaf(node) and is_left:
return node.val
return dfs(node.left, True) + dfs(node.right, False)
return dfs(root, False)
# Example usage:
# root = TreeNode(3)
# root.left = TreeNode(9)
# root.right = TreeNode(20)
# root.right.left = TreeNode(15)
# root.right.right = TreeNode(7)
# solution = Solution()
# print(solution.sumOfLeftLeaves(root)) # Output: 24
sumOfLeftLeaves
function initializes the recursive dfs
function.is_leaf
helper function checks if a node is a leaf.dfs
function traverses the tree, summing the values of left leaves:
By using the dfs
function recursively, the solution ensures that all left leaves are identified and their values summed appropriately. This approach works efficiently within the constraints provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?