binary tree
2
3
4
5
8
1
call stack ↓
(returned)
Concept
▸1sum(node):2 push frame3 if node is null: return 0 // base case4 return node.val + sum(left) + sum(right) // combine children's returns
state
- goaltotal of all node values
Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.
Try one problem▸1sum(node):2 push frame3 if node is null: return 0 // base case4 return node.val + sum(left) + sum(right) // combine children's returns
line 1Big idea: a child computes its own answer and RETURNS it; the parent COMBINES the children's returns into its own. We sum every value in the tree to see answers bubble UP from the leaves.