Binary Trees and Traversals
Traverse binary trees depth-first and breadth-first, and solve tree problems by combining answers returned from left and right subtrees.
Intermediate · about 8 hours · difficulty 3/5
Learn first: Recursion and Divide and Conquer, Queues and Deques
A binary tree node has up to two children. Tree problems are the best place to become fluent with recursion, because almost every solution follows the same shape: ask the left and right subtrees for something, then combine.
Traversals
- Preorder (node, left, right): copying or serialising a tree.
- Inorder (left, node, right): sorted order for a BST.
- Postorder (left, right, node): when a node needs its children's results first, like height or deleting a tree.
- Level order (BFS with a queue): level-by-level views, zigzag, right side view.
Know both recursive and iterative versions (iterative inorder with a stack is frequently asked).
Two recursion styles
- Bottom-up (return values): height, diameter, balanced check, maximum path sum. Return one value upward and update a global answer along the way.
- Top-down (pass parameters): pass down the current path sum, depth or allowed range.
Must-know problems
Maximum depth, diameter, same tree, invert tree, lowest common ancestor, path sum, construct tree from preorder + inorder, serialise/deserialise, and vertical or boundary traversal (popular in Indian interviews).
Pitfalls
Confusing height (edges vs nodes), null checks at leaves, and using a global variable without resetting it between test cases.
Key concepts
- Tree terminology and representation
- Pre, in, post-order traversal
- Level order traversal (BFS)
- Iterative traversals with a stack
- Bottom-up recursion (height, diameter)
- Top-down recursion (path sums)
- Lowest common ancestor
- Build tree from traversals
- Morris traversal: O(1) space inorder
Mini project
Solve 10 problems: Maximum Depth, Invert Binary Tree, Diameter of Binary Tree, Balanced Binary Tree, Binary Tree Level Order Traversal, Right Side View, Lowest Common Ancestor, Path Sum II, Construct Tree from Preorder and Inorder, and Binary Tree Maximum Path Sum.
Check yourself
In Binary Tree Maximum Path Sum, why is the value you return to the parent different from the value you use to update the global answer?
Free resources
- LeetCode Explore: Binary Tree (LeetCode)
- Binary tree data structure (GeeksforGeeks)
- NeetCode Roadmap (Trees) (NeetCode)