We have to return the sum of all left-leaf values in the tree. This means the left leaf of every subtree. So, it could be on a right child node, just that it has to be a leaf, and it has to be a left leaf at that.
In the code below, we detect any left leaves by the condition root.left and not root.left.left and not root.left.right
. If this condition meets, we return the root.left.val
and call the function on any right subtree that may or may not be present.
If a leaf is not detected, then make recursive calls on left
and right
subtrees as usual.
Code:
Python3
Big O Analysis
-
Runtime
The runtime complexity here is in the tree.
-
Memory
The memory usage would be of the implicit call stack we would use while recursion.
— A