0:00 / 0:00

Trust each child to answer, then combine the answers at the node. A missing child is the base case, and three lines of code solve most tree problems.

▼

Transcript

Welcome to the Trees world. A tree is a node with two smaller trees hanging below it. So here's the move: trust each child to answer for its subtree, then combine the answers at the node.

Ask the root lantern to count its family. It asks both children the same question, and the question flows down. A missing child answers zero: that's the base case. Then the answers flow back up. Each lantern adds its left and right, plus one: three plus two plus one is six.

In code, that's three lines. If the node is None, return zero. Call left and right. Combine.

Change only the combine, and the same shape answers other questions. One plus the taller side gives the height: three. Swap the two sides, and you've inverted the tree.

The clue: the problem says binary tree, root or subtree, or asks for a depth or a height.

Each node is visited once: linear time. The call stack holds one path, so the space is the tree's height.

Now let's use it on Invert Binary Tree.