Patterns: trees
This review of binary tree problems shows one template behind nearly all of them: decide what an empty tree returns, then combine the left and right answers; it also covers which traversal fits which job, and the exam formulas.
Tree problems look endlessly varied: depth, symmetry, paths, inverting, ancestors… but in interviews and exams nearly all of them are the same template; the rest is choosing the traversal order and a few formulas. This lesson has five steps: four patterns, then where the STL fits in. The code uses this chapter's node:
1struct TreeNode {2 int val;3 TreeNode *left, *right;4 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)5 : val(v), left(l), right(r) {}6};
Pattern one: ask left and right, combine
Writing tree recursion takes two decisions:
- What an empty tree gives (the answer at the bottom of the recursion);
- Given the left and right subtrees' answers, how to make this node's.
| To work out | An empty tree gives | How to combine |
|---|---|---|
| Number of nodes | 0 | left + right + 1 |
| Height | 0 | max(left, right) + 1 |
| Number of leaves | 0 | 1 for a leaf, otherwise left + right |
| Sum of all values | 0 | left + right + this value |
| Is there a node with value x | false | this one is x, or left has it, or right has it |
| Are two trees the same | the same only if both are empty | the same root, and left same as left, right as right |
The other kind passes things down: a parameter carries "what we know from the root to here" downwards, like how much of the path sum is still missing, or the range allowed (lo and hi when checking a binary search tree). Combining is postorder thinking, passing down is preorder thinking, and many problems use both.
Only check at a leaf. 5 → 4 sums to 9, but 4 isn't a leaf, so 9 doesn't count.
The template for height: an empty tree is 0; once you have the heights l and r of the two subtrees, what is this node's height? The tree is 1 (left child 2, right child 3); 2 has only a right child, 4, and 3 has only a left child, 5.
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct TreeNode {6 int val;7 TreeNode *left, *right;8 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)9 : val(v), left(l), right(r) {}10};11 12int height(TreeNode* t) {13 if (!t) return 0;14 int l = height(t->left), r = height(t->right);15 return ;16}17 18int main() {19 TreeNode* t = new TreeNode(1, new TreeNode(2, nullptr, new TreeNode(4)), new TreeNode(3, new TreeNode(5)));20 cout << height(t) << "\n";21 return 0;22}
l + r + 1 counts the nodes (5); without the + 1, a leaf has height 0 and so does everything above it.Invert a binary tree
✓Fill in invert: invert both subtrees first, then swap the left and right pointers. Inverted, its inorder should run largest to smallest.
9 7 6 4 3 2 1
1#include <iostream>2#include <utility>3using namespace std;4 5struct TreeNode {6 int val;7 TreeNode *left, *right;8 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)9 : val(v), left(l), right(r) {}10};11 12void invert(TreeNode* t) {13 // empty tree: return; invert left, invert right; swap t->left and t->right14}15 16void in(TreeNode* t) {17 if (!t) return;18 in(t->left);19 cout << t->val << " ";20 in(t->right);21}22 23int main() {24 TreeNode* t = new TreeNode(4, new TreeNode(2, new TreeNode(1), new TreeNode(3)),25 new TreeNode(7, new TreeNode(6), new TreeNode(9)));26 invert(t);27 in(t);28 cout << "\n";29 return 0;30}
Path sum
✓Is there a path from the root to a leaf whose values add up to exactly sum? Pass down "how much is still missing": at a leaf, check whether what's missing is exactly its value.
1 1 0
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11bool has_sum(TreeNode* t, int sum) {12 // empty tree: false; a leaf: sum == t->val; otherwise look for sum - t->val left and right13 return false;14}15 16int main() {17 // 518 // 4 819 // 11 13 420 // 7 2 121 TreeNode* t = new TreeNode(5,22 new TreeNode(4, new TreeNode(11, new TreeNode(7), new TreeNode(2))),23 new TreeNode(8, new TreeNode(13), new TreeNode(4, nullptr, new TreeNode(1))));24 cout << has_sum(t, 22) << " " << has_sum(t, 26) << " " << has_sum(t, 9) << "\n";25 return 0;26}
Pattern two: the right traversal
| Traversal | Good for | For example |
|---|---|---|
| Preorder | this node first, then the children: passing things down, copying a tree | printing a folder tree, path sums |
| Inorder | a binary search tree smallest to largest | the k-th smallest, checking a binary search tree |
| Postorder | needs the children's answers: height, deleting and freeing | freeing a whole tree, subtree sizes |
| Level order | by level, nearest the root | each level's largest, the minimum depth |
Freeing a whole tree has to be postorder: delete the two children first, this node last. delete t first and then reading t->left reads memory already handed back (the dangling pointer from Chapter 1). A tree's destructor is written this way.
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11int freed = 0;12 13void free_tree(TreeNode* t) {14 if (!t) return;15 free_tree(t->left); // the children first16 free_tree(t->right);17 cout << "free " << t->val << "\n";18 delete t; // this node last: postorder19 freed++;20}21 22int main() {23 TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4)), new TreeNode(3));24 free_tree(t);25 t = nullptr; // the pointer is still there, what it pointed at isn't: clear it so it isn't used again26 cout << freed << " freed in all\n";27 return 0;28}
free 4 free 2 free 3 free 1 4 freed in all
To find the 3rd smallest value in a binary search tree, which traversal fits best?
Pattern three: the formulas exam questions use
| The question asks | Formula |
|---|---|
| Leaves against nodes of degree 2 | n₀ = n₂ + 1 |
| The most nodes in a binary tree of height h | 2ʰ − 1 |
| The height of a complete binary tree of n nodes | ⌊log₂ n⌋ + 1 |
| How many leaves a complete binary tree of n nodes has | ⌈n / 2⌉ |
| Node i's children and parent in a complete binary tree (numbered from 1) | 2i, 2i + 1; ⌊i / 2⌋ |
| How many nodes a Huffman tree with n leaves has | 2n − 1 |
| How many shapes of binary tree n nodes can make | the Catalan number C(2n, n) / (n + 1), 5 for n = 3 |
A binary tree has 6 nodes of degree 2. How many leaves does it have?
A complete binary tree has 100 nodes. What is its height?
Pattern four: in a BST, compare and then go
A binary search tree comes with one more rule: everything in the left subtree is smaller than the root, everything in the right subtree bigger. So many problems don't need both sides: compare with the current node and the answer can only be on one side. One path down is enough, which takes O(h) (h is the height), not O(n). Search, insert, the minimum (keep going left) and the maximum (keep going right) all look like this:
1while (t) {2 if (x < t->val) t = t->left; // can only be on the left3 else if (x > t->val) t = t->right; // can only be on the right4 else return t; // this is it5}
The lowest common ancestor works the same way: if p and q are both smaller than the current node, go left; if both are bigger, go right. When one is on the left and one on the right (or one of them is the node itself), this is where the two values part ways, and the current node is the answer.
In this section's tree (6 2 8 0 4 7 9 3 5 inserted in that order), what is the lowest common ancestor of 7 and 9?
The lowest common ancestor in a binary search tree
✓The lowest common ancestor of two values p and q is the node where, walking down from the root, they first go different ways (or it's one of them). Both smaller than the current node: go left; both bigger: go right; otherwise it's this one.
6 4 2
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11TreeNode* insert(TreeNode* t, int v) {12 if (!t) return new TreeNode(v);13 if (v < t->val) t->left = insert(t->left, v);14 else if (v > t->val) t->right = insert(t->right, v);15 return t;16}17 18int lca(TreeNode* t, int p, int q) {19 // loop: p and q both < t->val, go left; both >, go right; otherwise return t->val20 return t->val;21}22 23int main() {24 TreeNode* t = nullptr;25 for (int x : {6, 2, 8, 0, 4, 7, 9, 3, 5})26 t = insert(t, x);27 cout << lca(t, 2, 8) << " " << lca(t, 3, 5) << " " << lca(t, 2, 4) << "\n";28 return 0;29}
With the STL
The STL doesn't hand you a tree (the red-black tree inside set / map won't let you touch its nodes), so tree problems still use your own TreeNode. The STL works alongside:
| To do | With | Why |
|---|---|---|
| Level order, per-level counts, minimum depth | queue<TreeNode*> | first in, first out: one level after another |
| Preorder or inorder without recursion | stack<TreeNode*> | your own call stack, no overflow on a very deep tree |
| Rebuild from preorder and inorder | unordered_map<int, int> of each value's inorder index | finding the root goes from O(n) to O(1), O(n) overall |
| Just look up, insert, delete in order | set / map | a hand-written binary search tree can lean; a red-black tree promises O(log n) |
| The k-th largest, merging the two smallest | priority_queue | a heap, O(log n) a time |
The level-order form that comes up most: at the start of each round, note how many are in the queue; that's exactly this level's node count.
1#include <iostream>2#include <vector>3#include <queue>4#include <algorithm>5using namespace std;6 7struct TreeNode {8 int val;9 TreeNode *left, *right;10 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)11 : val(v), left(l), right(r) {}12};13 14int main() {15 TreeNode* root = new TreeNode(1, new TreeNode(3, new TreeNode(5), new TreeNode(3)),16 new TreeNode(2, nullptr, new TreeNode(9)));17 queue<TreeNode*> q;18 q.push(root);19 int level = 1;20 vector<TreeNode*> all; // keep every node, delete them together at the end21 while (!q.empty()) {22 int n = q.size(), best = q.front()->val; // this level has n23 for (int i = 0; i < n; i++) {24 TreeNode* t = q.front(); q.pop();25 all.push_back(t);26 best = max(best, t->val);27 if (t->left) q.push(t->left);28 if (t->right) q.push(t->right);29 }30 cout << "level " << level++ << " largest: " << best << "\n";31 }32 for (TreeNode* t : all) delete t;33 return 0;34}
level 1 largest: 1 level 2 largest: 3 level 3 largest: 9
In interviews: with a tree problem, first say which pattern it is, "combine in postorder", "pass down in preorder" or "level order with a queue", then write the code; that usually reassures the interviewer. Recursive answers often get "what if the tree degenerates into a chain 100 000 deep": switch to the iterative form with a stack. For freeing, say postorder, or collect the nodes and delete them together as above.
When a level-order walk works level by level, each round starts with int n = q.size(); and then dequeues n nodes. What if you write for (int i = 0; i < (int)q.size(); i++) instead?
q.size() is how many are in the queue right now. Every node dequeued in the loop may put two children in, so the condition changes every round: the next level's nodes get counted before this level is done. Save this level's count in n first, and the loop runs exactly n times, one whole level.Summary
Three tree patterns
- The recursion template: what an empty tree gives + how to combine left and right; or pass things down
- Inorder = a binary search tree smallest first; postorder = wait for the children (height, delete); level order = queue
- Formulas: n₀ = n₂ + 1, 2ʰ − 1, ⌊log₂ n⌋ + 1, Huffman 2n − 1
- Free a tree in postorder: children first, then the node
1int f(TreeNode* t) {2 if (!t) return the empty tree's answer;3 int l = f(t->left), r = f(t->right);4 return combine l, r and t->val;5}
Chapter 4 quick check
5 questions: a traversal, a rebuild from traversals, a binary search tree's shape, lookups in a set, and a heap with Huffman. Work out what each prints before you pick.
1's left child is 2 (2 has only a right child, 4); its right child is 3 (3 has only a left child, 5). What does postorder print?
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11void post(TreeNode* t) {12 if (!t) return;13 post(t->left);14 post(t->right);15 cout << t->val << " ";16}17 18int main() {19 TreeNode* t = new TreeNode(1, new TreeNode(2, nullptr, new TreeNode(4)),20 new TreeNode(3, new TreeNode(5)));21 post(t);22 cout << "\n";23 return 0;24}
Preorder 1 2 4 5 3 6, inorder 4 2 5 1 3 6: what does the rebuilt tree print in postorder?
1#include <iostream>2#include <vector>3using namespace std;4 5struct TreeNode {6 int val;7 TreeNode *left, *right;8 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)9 : val(v), left(l), right(r) {}10};11 12vector<int> pre = {1, 2, 4, 5, 3, 6}, in = {4, 2, 5, 1, 3, 6};13 14// pre[p] is the root; its place in the inorder in[lo..hi] splits left from right15TreeNode* build(int p, int lo, int hi) {16 if (lo > hi) return nullptr;17 int m = lo;18 while (in[m] != pre[p]) m++;19 int leftSize = m - lo;20 return new TreeNode(pre[p], build(p + 1, lo, m - 1),21 build(p + 1 + leftSize, m + 1, hi));22}23 24void post(TreeNode* t) {25 if (!t) return;26 post(t->left);27 post(t->right);28 cout << t->val << " ";29}30 31int main() {32 post(build(0, 0, 5));33 cout << "\n";34 return 0;35}
Inserting 10 9 8 20 30 40 7 in turn: how tall is the binary search tree?
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct TreeNode {6 int val;7 TreeNode *left, *right;8 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)9 : val(v), left(l), right(r) {}10};11 12TreeNode* insert(TreeNode* t, int v) {13 if (!t) return new TreeNode(v);14 if (v < t->val) t->left = insert(t->left, v);15 else if (v > t->val) t->right = insert(t->right, v);16 return t;17}18 19int height(TreeNode* t) {20 if (!t) return 0;21 return max(height(t->left), height(t->right)) + 1;22}23 24int main() {25 TreeNode* t = nullptr;26 for (int x : {10, 9, 8, 20, 30, 40, 7})27 t = insert(t, x);28 cout << height(t) << "\n";29 return 0;30}
Putting 5 1 4 1 3 into a set in turn: what's printed?
1#include <iostream>2#include <set>3using namespace std;4 5int main() {6 set<int> s;7 for (int x : {5, 1, 4, 1, 3})8 s.insert(x);9 cout << s.size() << " " << *s.begin() << " "10 << *s.lower_bound(2) << " " << *s.upper_bound(4) << "\n";11 return 0;12}
The Huffman tree for weights 7, 2, 5, 3: what's left in the heap at the end, and what's the WPL?
1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5using namespace std;6 7int main() {8 priority_queue<int, vector<int>, greater<int>> q;9 for (int x : {7, 2, 5, 3})10 q.push(x);11 int wpl = 0;12 while (q.size() > 1) {13 int a = q.top(); q.pop();14 int b = q.top(); q.pop();15 wpl += a + b;16 q.push(a + b);17 }18 cout << q.top() << " " << wpl << "\n";19 return 0;20}