Learn the pattern · ~15 min
Tree Construction & Serialization
also called rebuild from traversals, encode/decode tree
Preorder tells you who the root is, inorder tells you where to split; a value → index map makes each split O(1), and you recurse on index ranges, never on copies.
Reach for it when you read
- +You are given two traversals (preorder or postorder, plus inorder) and must rebuild the tree.
- +Build a balanced BST from a sorted array or list: the middle is the root.
- +Rebuild a BST from its preorder alone: bounds stand in for inorder.
- +Turn a tree into a string and back (serialize / deserialize), or compare subtrees by a fingerprint string.
Not this one when
- ×Preorder + postorder with no inorder: the split is ambiguous when a node has one child; that problem promises a full binary tree.
- ×Values repeat: the inorder split isn't unique, so the map trick (and the uniqueness of the answer) breaks.
- ×Only asked whether a preorder string with
#for nulls is valid (Verify Preorder Serialization): count open child slots; no tree is built.
Learn Tree Construction & Serialization
First, what are preorder, inorder and postorder?
Three ways to write a tree as a list. All walk left subtree before right; they differ only in when a node writes itself down:
- preorder: the node first, then its left subtree, then its right subtree.
- inorder: left subtree, then the node, then right subtree.
- postorder: left subtree, right subtree, then the node last.
Tiny example: a root 2 with a left child 1 and a right child 3. Preorder is 2 1 3, inorder is 1 2 3, postorder is 1 3 2.
Tree construction goes backwards: given two of these lists, rebuild the tree.
What do the lists tell you?
Here's our tree:
5
/ \
2 8
/ \ \
1 3 9
\
4- inorder:
1 2 3 4 5 8 9 - postorder:
1 4 3 2 9 8 5
The rule:
The last value of postorder is the root. Its position in inorder splits everything else into left and right. The left side's size then cuts postorder too.
| step | what happens | left subtree | root | right subtree |
|---|---|---|---|---|
| 1 | postorder ends with 5, so 5 is the root | ? | 5 | ? |
| 2 | find 5 in inorder: four values before it, two after | inorder 1 2 3 4 |
5 | inorder 8 9 |
| 3 | postorder lists the left subtree first: its first four values, then two for the right | postorder 1 4 3 2 |
5 | postorder 9 8 |
Each side is now the same question, smaller: rebuild 1 2 3 4 / 1 4 3 2. Its root is the last value, 2.
The code for it
The three orders are one walk with the write in three different places:
void walk(TreeNode* node) {
if (!node) return;
P.push_back(node->val); // preorder: the node before its subtrees
walk(node->left);
I.push_back(node->val); // inorder: between left and right
walk(node->right);
O.push_back(node->val); // postorder: after both subtrees
}On our tree it fills P = 5 2 1 3 4 8 9, I = 1 2 3 4 5 8 9 and O = 1 4 3 2 9 8 5.
You don't need to memorise this: before, between, after.
Why is every subtree one unbroken block in every list? Once walk(2) starts, nothing outside 2's subtree is written until it returns. That's why step 3 can cut postorder by size alone.
Fine, but how does this help us?
Here's the classic problem: construct a binary tree from inorder and postorder, with distinct values. Given 1 2 3 4 5 8 9 and 1 4 3 2 9 8 5, return the tree. By hand, apply the rule to each block:
| blocks (inorder / postorder) | last of postorder = root | inorder split around it |
|---|---|---|
1 2 3 4 5 8 9 / 1 4 3 2 9 8 5 |
5 | 1 2 3 4 · 5 · 8 9 |
1 2 3 4 / 1 4 3 2 |
2 | 1 · 2 · 3 4 |
1 / 1 |
1 | nothing on either side: a leaf |
3 4 / 4 3 |
3 | nothing on the left · 3 · 4 |
4 / 4 |
4 | a leaf, the right child of 3 |
8 9 / 9 8 |
8 | nothing on the left · 8 · 9 |
9 / 9 |
9 | a leaf |
That's the tree in the picture; its preorder is 5 2 1 3 4 8 9.
The brute force
Do what the table says: scan inorder for the root, copy both sides into new arrays, recurse.
TreeNode* buildBrute(vector<int> in, vector<int> post) {
if (in.empty()) return nullptr;
TreeNode* root = new TreeNode(post.back()); // postorder ends with the root
int i = 0;
while (in[i] != root->val) i++; // scan inorder for it
root->left = buildBrute(vector<int>(in.begin(), in.begin() + i),
vector<int>(post.begin(), post.begin() + i));
root->right = buildBrute(vector<int>(in.begin() + i + 1, in.end()),
vector<int>(post.begin() + i, post.end() - 1));
return root;
}It works. But take a tree leaning left, each node the left child of the one before. Each root is then the last value of its inorder block, so the scan walks the whole block, and the copies cost as much again: n + (n − 1) + … + 1 ≈ n²/2 each. LeetCode allows 3,000 nodes, so it passes there in milliseconds. At n = 10⁵ it takes 11 seconds (-O2): time limit exceeded.
The one thought that fixes it
Stop at the second row: 1 2 3 4 / 1 4 3 2. The brute force copies those eight numbers into new arrays. But they already sit side by side in the original lists, at inorder positions 0 to 3 and postorder 0 to 3: the block property. So a call needs no copies, only where its block starts in each list and how long it is: (0, 0, 4).
And the scan for 2 in inorder? Values are distinct, so each has one fixed inorder position. Build a map value → inorder index once, and every root is found in O(1).
unordered_map<int, int> pos; // value -> its index in inorder
vector<int> post;
// one subtree: `size` values starting at in[inStart] and at post[postStart]
TreeNode* build(int inStart, int postStart, int size) {
if (size == 0) return nullptr;
TreeNode* root = new TreeNode(post[postStart + size - 1]); // the block's last value
int i = pos[root->val];
int leftSize = i - inStart; // left block, root, right block
root->left = build(inStart, postStart, leftSize);
root->right = build(i + 1, postStart + leftSize, size - 1 - leftSize);
return root;
}Fill pos[in[k]] = k and post, then call build(0, 0, n).
Slow down on the right subtree: in inorder it starts after the root (i + 1), in postorder right after the left block (postStart + leftSize), and it's size − 1 − leftSize long because the root takes the last slot.
Dry run
Every non-empty call, in order; the call stack lists the roots of the calls still open:
| call (inStart, postStart, size) | root | left size | right size | call stack |
|---|---|---|---|---|
| (0, 0, 7) | 5 | 4 | 2 | 5 |
| (0, 0, 4) | 2 | 1 | 2 | 5, 2 |
| (0, 0, 1) | 1 | 0 | 0 | 5, 2, 1 |
| (2, 1, 2) | 3 | 0 | 1 | 5, 2, 3 |
| (3, 1, 1) | 4 | 0 | 0 | 5, 2, 3, 4 |
| (5, 4, 2) | 8 | 0 | 1 | 5, 8 |
| (6, 4, 1) | 9 | 0 | 0 | 5, 8, 9 |
Row 4: 3's block starts at inorder 2 (after 1 2) but at postorder 1 (after just 1): postorder writes 2 after its subtrees, not between them. The result's preorder is 5 2 1 3 4 8 9, the same answer as the brute force.
Why it's O(n)
Count what happens to each value: it is the root of exactly one non-empty call, which does one lookup and makes one node. The n + 1 empty calls return at once: O(n) time. The map holds n entries and the stack up to n calls on a chain: O(n) space.
From O(n²) to O(n), by passing positions instead of copies and looking roots up instead of scanning.
Preorder and inorder? The root moves to the front
Preorder starts with the root, and the left block comes right after it. Only these lines change:
TreeNode* root = new TreeNode(preo[preStart]); // preorder starts with the root
int i = pos[root->val], leftSize = i - inStart;
root->left = buildPre(inStart, preStart + 1, leftSize); // the left block follows the root
root->right = buildPre(i + 1, preStart + 1 + leftSize, size - 1 - leftSize);With preorder 5 2 1 3 4 8 9 and the same inorder, it builds the same tree (its postorder is 1 4 3 2 9 8 5).
A sorted array to a balanced BST? The middle is the root
A sorted array is a BST's inorder. Make the middle the root so each side gets half:
TreeNode* fromSorted(const vector<int>& a, int lo, int hi) {
if (lo > hi) return nullptr;
int mid = (lo + hi) / 2; // the middle is the root
TreeNode* root = new TreeNode(a[mid]);
root->left = fromSorted(a, lo, mid - 1);
root->right = fromSorted(a, mid + 1, hi);
return root;
}From 1 2 3 4 5 8 9 the middle is 4:
4
/ \
2 8
/ \ / \
1 3 5 9Remember this
- Root from preorder (first) or postorder (last); the split from inorder; the left size cuts the other list.
- Pass start positions and a size, never copies; find roots with a
value → indexmap. - Values must be distinct, or the split isn't unique.
- Whenever a problem gives you two traversals or a sorted sequence and wants a tree back, it's this.
Practise it on Convert Sorted Array to Binary Search Tree, then Construct Binary Tree from Preorder and Inorder Traversal, Construct Binary Tree from Inorder and Postorder Traversal, Tree Traversals (print the postorder without building the tree), Construct BST from Preorder Traversal (bounds instead of inorder) and Serialize and Deserialize Binary Tree (null markers instead of a second list).
Below, watch Construct Binary Tree from Preorder and Inorder Traversal run line by line.
Watch it work, line by line
Construct Binary Tree from Preorder and Inorder Traversal ↗, preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7] → [3, 9, 20, null, null, 15, 7]. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
At each step, do I know which value is the root, and which values belong to each side?
Reach for it when
- +given two traversals, build the tree
- +serialize/deserialize
- +flatten/convert structure
- +n up to 1e4; unique values usually required
It fails when
- ×Values have duplicates: the inorder split is ambiguoususe Build from unique ids, or serialize with null markers
- ×Only preorder + postorder are given: not unique unless the tree is fulluse Need inorder, or a full-tree guarantee
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1Which traversal tells you the root, and which one tells you the split?Reveal
Preorder (first value) or postorder (last value) gives the root. Inorder splits the rest into left and right.
2Why build a value → index map first?Reveal
Finding the root in inorder by scanning is O(n) each time, which is O(n²) on a skewed tree. The map makes each split O(1).
3Why must a serialized tree include null markers?Reveal
Without them different trees give the same string:
1,2could be 2 as a left child or as a right child.
Practice ladder
- 1Convert Sorted Array to Binary Search Treesorted array → BSTEasy
- 2Construct Binary Tree from Preorder and Inorder Traversalthe hookMedium
- 3Construct Binary Tree from Inorder and Postorder Traversalpostorder + inorderMedium
- 4Tree Traversalsprint without buildingMedium
- 5Construct Binary Search Tree from Preorder Traversalbounds instead of inorderMedium
- 6Flatten Binary Tree to Linked Listrewire in placeMedium
- 7Find Duplicate Subtreesserialization as a fingerprintMedium
- 8Serialize and Deserialize Binary Treeserialize with null markersHard
Finished Tree Construction & Serialization? Mark it done and Lessgo moves you to the next step.