Binary tree
easy 18 minA binary tree is a hierarchy of nodes where each node has at most two children, left and right, hanging from a single root.
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
Two kids max: left and right, one root at the top, leaves at the bottom.
A family tree drawn upside down: the oldest ancestor at the top, each person with at most two children underneath. Depth is how many generations down you are; height is how many generations still come after you.
Cheat sheet
- Children per node
- at most 2
- Edges
- n − 1
- Max nodes, height h
- 2^(h+1) − 1
- Height range
- ⌊log₂ n⌋ to n − 1
- Array children
- 2i + 1, 2i + 2
- Array parent
- (i − 1) // 2
- Traversal time
- O(n)
- DFS space
- O(h)
- BFS space
- O(w)
Spot it when you see
- Data has a natural hierarchy or a two-way choice at each step.
- The answer needs something from both children first: postorder.
- The question says level, row, nearest or shallowest: BFS.
- A heap or priority queue is involved: a complete tree in an array.
- Rebuilding a tree from two traversal lists.
Tricks that stick
- PRE, IN, POST tell you where the node goes: before, in between, or after its two children. Left always beats right.
- LNR, NLR, LRN: only the N moves.
- Cave story: preorder plants a flag on entering each room, inorder marks it between the left and right tunnels, postorder marks it on the way out.
- IN for sorted: inorder of a BST is in order.
- Depth looks down from the root; height looks up from the leaves.
- Double the index and add 1 or 2 to go down; subtract 1 and halve to go up.
Do not forget
- No None check before reading node.left.
- Mixing height in edges with depth in nodes.
- Assuming the tree is balanced; a chain is O(n) deep.
- Putting the append in the wrong place and getting the wrong traversal.
- Recursion limit on deep, skewed trees in Python.
- Forgetting to ask: binary tree or binary search tree?