By: Saurav
2018-04-02 08:22:00 UTC
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
def sum_of_left_leaves(root) return 0 if !root return dfs(root, 0) end def dfs(root, sum) return sum if !root if root.left and !root.left.left and !root.left.right sum += root.left.val end #p "dfs(#{root}, #{sum})" sum = dfs(root.left, sum) sum = dfs(root.right, sum) return sum end
Owned & Maintained by Saurav Prakash
If you like what you see, you can help me cover server costs or buy me a cup of coffee though donation :)