404. Sum of Left Leaves

Overview
We need to find the sum of the left leaves of a binary tree.
The left leaves cannot have any child nodes, including left child nodes and right child nodes.
We will separately use DFS and BFS to resolve this problem.
Solution 1: Depth-first search (DFS)
Algorithm
Make sumOfLeftLeaves a recursive function.
-
If the
rootnode is None, return 0. -
If the
leftnode of therootnode is not None
and theleftnode of theleftnode of therootnode is None
and therightnode of theleftnode of therootnode is None:- Return the
valueof theleftnode of therootnode
plussumOfLeftLeaveswith therightnode of therootnode.
We only find the sum of the left nodes which don't have child nodes.
- Return the
-
Return
sumOfLeftLeaveswith theleftnode of therootnode plussumOfLeftLeaveswith therightnode of therootnode.\We'll recursively start from the root node to the deepest node.
Implement
class Solution: def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: if root is None: return 0 if root.left and root.left.left is None and root.left.right is None: return root.left.val + self.sumOfLeftLeaves(root.right) return self.sumOfLeftLeaves(root.left) + \ self.sumOfLeftLeaves(root.right)
Complexity Analysis
Time complexity: O(n)
We traverse all nodes of the binary tree, which takes O(n) time.
Space complexity: O(n)
The recursive function uses memory to store the function state, which takes O(n) space.
Solution 2: Breadth-first search (BFS)
Algorithm
Without using a recursive function, we use queue instead.
-
Initialize
totalto 0 to store the sum of the left nodes' values.
Initializequeueto store the nodes at the same depth that we'll traverse. -
If
queueis not empty:-
Pop the leftmost node of
queueasnode. -
If the
leftnode of thenodeis not None
and theleftnode of theleftnode of thenodeis None
and therightnode of theleftnode of thenodeis None:- Increase
totalby thevalueof theleftnode of thenode.
- Increase
-
If the
leftnode of thenodeis not None:- Append the
leftnode of thenodetoqueuefor the next traversal.
- Append the
-
If the
rightnode of thenodeis not None:- Append the
rightnode of thenodetoqueuefor the next traversal.
- Append the
-
-
Return
totalas the sum of the left nodes which don't have child nodes.
Implement
class Solution: def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: total = 0 queue = deque([root]) while queue: node = queue.popleft() if node.left and node.left.left is None and node.left.right is None: total += node.left.val if node.left is not None: queue.append(node.left) if node.right is not None: queue.append(node.right) return total
Complexity Analysis
Time complexity: O(n)
We traverse all nodes of the binary tree, which takes O(n) time.
Space complexity: O(1)
The queue at most takes the maximum number of nodes at the same depth,
which are always fewer than the total number of nodes in the binary tree.