Rebuilding a tree from its traversals
Rebuilding a binary tree from preorder and inorder is recursive: the preorder's first value is the root, its place in the inorder splits left from right, then repeat on each part; an unordered_map of positions makes it O(n).
Last lesson went "here is a tree, write the sequence". Exams prefer it the other way round: here are two sequences, draw the tree. For example, preorder A B D E C F and inorder D B E A C F: what does the tree look like?
Each sequence tells you one thing
- The first in preorder is always the root (root, left, right: the root comes first). The last in postorder is the root too.
- In inorder, everything left of the root is the left subtree and everything right of it the right subtree (left, root, right).
Once you know the root, you can cut the inorder sequence into a left part and a right part; once you know how many are on the left, you can cut the preorder into the matching two parts. Then do the same thing to each part.
Finally, check with the third traversal: this tree's postorder should be D E B F C A.
The preorder is A B D C E F and the inorder B D A E C F. Draw the tree: what is its postorder?
The postorder is C B E F D A and the inorder B C A E D F. What is the preorder?
Drawing a tree from its preorder and inorder: put the four steps in order.
Do the same again for each of the two partsCount k nodes in the left subtree: the k after the root in the preorder are the left subtree, the rest the right oneFind the root in the inorder: what is left of it is the left subtree, what is right of it the right subtreeTake the first in the preorder: it is the root
Writing it in C++
Turn the cutting from the first level straight into recursion. A part of a sequence is given by "where it starts, how long it is": build(pre, p, in, i, n) builds a tree from the n values starting at p in the preorder and at i in the inorder. The root is pre[p]; find it in this part of the inorder, with k values to its left; the left subtree is the k values starting at p + 1 in the preorder and at i in the inorder, the right subtree the n − 1 − k values starting at p + 1 + k and at i + k + 1. The values are letters, so val is a char.
1#include <iostream>2#include <string>3using namespace std;4 5struct TreeNode {6 char val;7 TreeNode *left, *right;8 TreeNode(char v) : val(v), left(nullptr), right(nullptr) {}9};10 11TreeNode* build(const string& pre, int p, const string& in, int i, int n) {12 if (n == 0) return nullptr;13 TreeNode* t = new TreeNode(pre[p]); // the first in preorder is the root14 int k = 0;15 while (in[i + k] != pre[p]) k++; // the root's place in the inorder: k on its left16 t->left = build(pre, p + 1, in, i, k);17 t->right = build(pre, p + 1 + k, in, i + k + 1, n - 1 - k);18 return t;19}20 21void post(TreeNode* t) {22 if (!t) return;23 post(t->left);24 post(t->right);25 cout << t->val << ' ';26}27 28void destroy(TreeNode* t) {29 if (!t) return;30 destroy(t->left);31 destroy(t->right);32 delete t;33}34 35int main() {36 TreeNode* t = build("ABDECF", 0, "DBEACF", 0, 6);37 cout << "postorder: ";38 post(t);39 cout << endl;40 destroy(t);41 return 0;42}
postorder: D E B F C A
pre and in are passed as const string&: each level of recursion passes only a reference, and the strings are never copied. Each level searches the inorder for the root once, which at worst (the tree is a chain) is O(n²); note down each value's position in the inorder first and it drops to O(n), which is what the STL version in the last level does.
Preorder A B C D, inorder D C B A. How tall is the tree that gets built?
1#include <iostream>2#include <string>3#include <algorithm>4using namespace std;5 6struct TreeNode {7 char val;8 TreeNode *left, *right;9 TreeNode(char v) : val(v), left(nullptr), right(nullptr) {}10};11 12TreeNode* build(const string& pre, int p, const string& in, int i, int n) {13 if (n == 0) return nullptr;14 TreeNode* t = new TreeNode(pre[p]);15 int k = 0;16 while (in[i + k] != pre[p]) k++;17 t->left = build(pre, p + 1, in, i, k);18 t->right = build(pre, p + 1 + k, in, i + k + 1, n - 1 - k);19 return t;20}21 22int height(TreeNode* t) {23 if (!t) return 0;24 return max(height(t->left), height(t->right)) + 1;25}26 27int main() {28 cout << height(build("ABCD", 0, "DCBA", 0, 4)) << endl;29 return 0;30}
How many nodes are in the right subtree? Pick what goes in the blank so the program prints the tree's postorder, DEBFCA.
1#include <iostream>2#include <string>3using namespace std;4 5struct TreeNode {6 char val;7 TreeNode *left, *right;8 TreeNode(char v) : val(v), left(nullptr), right(nullptr) {}9};10 11TreeNode* build(const string& pre, int p, const string& in, int i, int n) {12 if (n == 0) return nullptr;13 TreeNode* t = new TreeNode(pre[p]);14 int k = 0;15 while (in[i + k] != pre[p]) k++;16 t->left = build(pre, p + 1, in, i, k);17 t->right = build(pre, p + 1 + k, in, i + k + 1, );18 return t;19}20 21void post(TreeNode* t) {22 if (!t) return;23 post(t->left);24 post(t->right);25 cout << t->val;26}27 28int main() {29 post(build("ABDECF", 0, "DBEACF", 0, 6));30 cout << "\n";31 return 0;32}
n - k counts one too many and reads past the end of the string.How long does this step's build take in the worst case?
Building from postorder + inorder
✓Finish build so it builds the tree from the postorder and the inorder. The root is the last in this part of the postorder; the left subtree is the k values starting at p in the postorder, the right subtree the n − 1 − k after them.
ABDCEGFH
1#include <iostream>2#include <string>3using namespace std;4 5struct TreeNode {6 char val;7 TreeNode *left, *right;8 TreeNode(char v) : val(v), left(nullptr), right(nullptr) {}9};10 11TreeNode* build(const string& post, int p, const string& in, int i, int n) {12 if (n == 0) return nullptr;13 TreeNode* t = new TreeNode(post[p + n - 1]);14 // find the root in this part of the inorder, with k on its left; then build the two subtrees15 return t;16}17 18void pre(TreeNode* t) {19 if (!t) return;20 cout << t->val;21 pre(t->left);22 pre(t->right);23}24 25int main() {26 pre(build("DBGEHFCA", 0, "BDAGECHF", 0, 8));27 cout << endl;28 return 0;29}
The postorder, without building a tree
✓Build no tree: post_of makes the same cuts in the preorder and inorder and prints in the order "left part, right part, root", which prints the postorder.
AEFDHZMG
1#include <iostream>2#include <string>3using namespace std;4 5void post_of(const string& pre, int p, const string& in, int i, int n) {6 // return if n == 0; find the root in the inorder, with k on its left; left part, right part, then print the root pre[p]7}8 9int main() {10 post_of("GDAFEMHZ", 0, "ADEFGHMZ", 0, 8);11 cout << endl;12 return 0;13}
Which two sequences fix one tree
| Sequences given | One tree for certain? | Why |
|---|---|---|
| Preorder + inorder | Yes | Preorder gives the root, inorder splits left from right |
| Postorder + inorder | Yes | The last in postorder is the root, inorder splits left from right |
| Level order + inorder | Yes | The first in level order is the root, inorder splits left from right |
| Preorder + postorder | No | You know the root, but can't tell left from right |
Why preorder + postorder fails: one tree is just A with a left child B, another just A with a right child B; both have preorder A B and postorder B A. You need the inorder to tell left from right.
In exams: For postorder + inorder, take the root from the end of the postorder; once you have cut the left and right parts, the first part of the postorder is the left subtree, the part right after it the right subtree, and the root comes last. Always check your drawing with the third sequence.
A binary tree's preorder and postorder are exact reverses of each other (say, preorder A B C and postorder C B A). What must the tree look like?
How many binary trees have the preorder A B C and the postorder C B A?
With the STL
There is only one slow spot: searching the inorder for the root from the start every time. If the values are all different, first put "value → index in the inorder" into an unordered_map, and finding the root is one lookup, O(1) on average. On a chain of 500 nodes (preorder 1, 2, …, 500, inorder the other way round), count how many steps each version takes to find the roots:
1#include <iostream>2#include <vector>3#include <unordered_map>4using namespace std;5 6struct TreeNode {7 int val;8 TreeNode *left, *right;9 TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}10};11 12long steps = 0;13 14TreeNode* build_scan(const vector<int>& pre, int p, const vector<int>& in, int i, int n) {15 if (n == 0) return nullptr;16 TreeNode* t = new TreeNode(pre[p]);17 int k = 0;18 while (in[i + k] != pre[p]) { // search one by one19 k++;20 steps++;21 }22 t->left = build_scan(pre, p + 1, in, i, k);23 t->right = build_scan(pre, p + 1 + k, in, i + k + 1, n - 1 - k);24 return t;25}26 27unordered_map<int, int> pos; // value → index in the inorder28 29TreeNode* build_map(const vector<int>& pre, int p, int i, int n) {30 if (n == 0) return nullptr;31 TreeNode* t = new TreeNode(pre[p]);32 int k = pos[pre[p]] - i; // one lookup33 steps++;34 t->left = build_map(pre, p + 1, i, k);35 t->right = build_map(pre, p + 1 + k, i + k + 1, n - 1 - k);36 return t;37}38 39void destroy(TreeNode* t) {40 if (!t) return;41 destroy(t->left);42 destroy(t->right);43 delete t;44}45 46int main() {47 int n = 500;48 vector<int> pre, in;49 for (int v = 1; v <= n; v++) pre.push_back(v);50 for (int v = n; v >= 1; v--) in.push_back(v);51 52 TreeNode* a = build_scan(pre, 0, in, 0, n);53 cout << "searching: " << steps << " steps" << endl;54 55 for (int j = 0; j < n; j++) pos[in[j]] = j;56 steps = 0;57 TreeNode* b = build_map(pre, 0, 0, n);58 cout << "lookup: " << steps << " steps" << endl;59 cout << "the two roots: " << a->val << " " << b->val << endl;60 destroy(a);61 destroy(b);62 return 0;63}
searching: 124750 steps lookup: 500 steps the two roots: 1 1
Searching takes 0 + 1 + … + 499 ≈ n² / 2 steps; the lookup is once per node, exactly n steps. Inside, an unordered_map is a row of buckets, each with a chain hanging from it: the key's hash says which bucket to go to, O(1) on average, and building the table is O(n). When the values are small integers such as 0 to 1000, a vector<int> pos(1001) as the table is simpler, and O(1) too.
| Finding the root | Each time | Building the whole tree |
|---|---|---|
| Searching the inorder one by one | O(n) | O(n²) at worst, O(n log n) for an even tree |
Looking up the position in an unordered_map | O(1) on average | O(n) |
In interviews: The standard answer to LeetCode 105 (preorder + inorder) and 106 (postorder + inorder) is "positions in an unordered_map + pass only indexes". The problem will say "the values are distinct": with repeated values, a lookup can't tell which one you mean, and the tree may not be unique.
LeetCode 105 says "the values in the tree are all different". Why does the lookup-table version need that?
pos[v] holds one position. If the inorder has two 2s and the root is 2, you can't tell at which 2 to cut, and such trees may not be unique anyway. unordered_map doesn't complain about a repeated key: the later value just overwrites the earlier one.Summary
A tree from two sequences: one gives the root, inorder splits the sides
- The first in preorder / the last in postorder is the root
- In the inorder, left of the root is the left subtree, right of it the right; count the k on the left
- Cut the other sequence into two parts by k too, and do each part the same way; positions in an unordered_map make it O(n)
- Preorder + postorder can't fix one tree: you need the inorder
1TreeNode* t = new TreeNode(pre[p]);2while (in[i + k] != pre[p]) k++;3t->left = build(pre, p + 1, in, i, k);4t->right = build(pre, p + 1 + k, in, i + k + 1, n - 1 - k);