Problem Description
Given the root of a binary tree, return the sum of all left leaves. A left leaf is a node that is the left child of its parent and does not have any children.
Key Insights
- Use recursion or iteration (DFS/BFS) to traverse the binary tree.
- At each node, check if the left child is a leaf (has no children).
- Sum up the values of all left leaves.
- Ensure all nodes are checked, even if the immediate left child is not a leaf.
Space and Time Complexity
Time Complexity: O(n) where n is the number of nodes in the tree, because every node is visited exactly once. Space Complexity: O(n) in the worst case, due to recursion stack space if the tree is skewed.
Solution
We use a Depth-First Search (DFS) recursive approach. At each node, check if the left child exists and is a leaf. If so, add its value to the sum. Regardless, recursively call the function for both the left and right children (if applicable) to explore the entire tree. The base case for recursion is when the current node is null. This method ensures that all nodes are properly evaluated while maintaining clarity and simplicity.