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 another node.
Example 1:
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.
Example 2:
Input: root = [1] Output: 0
Constraints:
[1, 1000].-1000 <= Node.val <= 1000This approach involves using recursive DFS to traverse the tree. At each node, determine if it is a left leaf. If it is, add its value to the sum and recursively continue to search for more left leaves in the subtree.
We define a helper function dfs which takes a node and a boolean indicating whether it is a left child. If the node is a leaf and is a left child, we add its value to the sum. Otherwise, recurse into the left and right subtrees.
C++
Java
Python
C#
JavaScript
The time complexity is O(n) where n is the number of nodes, as we visit each node once. The space complexity is O(h), where h is the height of the tree, due to the recursive call stack.
This approach applies iterative DFS using a stack. By exploring each node iteratively, it checks if a node qualifies as a left leaf and accumulates its value to the sum. It manages to mimic a recursive pattern iteratively.
This C solution uses a custom stack to perform an iterative DFS. It pushes nodes onto the stack and processes them. If deemed a left leaf, its value contributes to the sum. By simulating recursion iteratively, this approach eliminates associated stack memory drawbacks.
C++
Java
Python
C#
JavaScript
The time complexity is O(n) for navigating each tree node once. Space complexity is O(n) due to maintaining a stack proportional to the number of nodes.
| Approach | Complexity |
|---|---|
| Recursive Depth-First Search (DFS) | The time complexity is O(n) where n is the number of nodes, as we visit each node once. The space complexity is O(h), where h is the height of the tree, due to the recursive call stack. |
| Iterative Depth-First Search | The time complexity is O(n) for navigating each tree node once. Space complexity is O(n) due to maintaining a stack proportional to the number of nodes. |
Sum of Left Leaves • Kevin Naughton Jr. • 25,663 views views
Watch 9 more video solutions →Practice Sum of Left Leaves with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor