Last Updated: March 29, 2026
We're given a binary tree and need to find the sum of values of all "left leaves." Two conditions must both be true for a node to count: it must be a leaf (no left or right child), and it must be the left child of its parent.
The tricky part here is that we can't determine if a node is a "left leaf" just by looking at the node itself. A leaf node doesn't know whether it's a left child or a right child. We need information from the parent. So the key observation is this: when we visit a node, we should check if its left child is a leaf. If it is, we add that child's value to our sum. We don't add the current node's value, we add its left child's value when that child has no children of its own.
This parent-checks-child approach is simpler and cleaner than passing a flag like "am I a left child?" through recursion, though both work.
Number of nodes in [1, 1000] --> The tree is small. Any standard traversal gives us O(n), which is optimal since we must visit every node.-1000 <= Node.val <= 1000 --> Values can be negative, so a left leaf might subtract from the total. We can't skip negative values.At least 1 node --> The root always exists, but it might be a single node with no children (answer would be 0 since the root itself is not a "left" child of anything).The most natural way to process a binary tree is with recursion. We visit each node, and at each node, we ask one simple question: is my left child a leaf?
A left child is a leaf if it exists but has no children of its own (both left.left and left.right are null). If that's the case, we take its value. Then we recurse into both the left subtree and the right subtree to find any other left leaves deeper in the tree.
Notice we don't add the current node's value. We're always looking one level down, checking whether the left child qualifies. This avoids the need for any "isLeft" flag in the recursion.
null, return 0.sum = 0.left.val to sum.sum.sum.sum.The recursive approach is clean and optimal in time, but it uses the call stack. For very deep trees, this could cause a stack overflow. Can we solve it iteratively instead?
Instead of recursion, we can use a queue to traverse the tree level by level. The core logic stays exactly the same: for each node we process, check if its left child is a leaf. If so, add the left child's value to our running total.
BFS has a different space profile than DFS. Instead of space proportional to the tree's height, it uses space proportional to the tree's maximum width. For skewed trees (where recursion is most dangerous), BFS uses only O(1) space since each level has just one node.
root is null, return 0.root to it.sum = 0.left.val to sum.sum.