0
Challenge · 44Trees

Depth, balance and diameter

Treesused in ~85% of apps

Three questions that all sound different and all have the same answer: let each child report one number upward, and work out your own from theirs. Once you see that shape, a whole class of tree problems stops being hard.

Core idea. A node cannot answer anything about itself until its children have reported. So the pattern is postorder: recurse first, receive a number from each side, then combine. The clever part in harder versions is returning one thing upward while quietly tracking a different thing on the side.
Playground, this isn't a screenshot
the same seven nodes, visited in three different orders
nothing visited yet

Same walk every time. Only the moment you write the number down changes.

↑ play a little first, then dig in