Construct binary tree from inorder and postorder traversal, explained
To rebuild a binary tree from its inorder and postorder sequences, take the last postorder value as the root, find it in the inorder sequence to split the remaining values into the left and right subtrees, and recurse. The fast version stores each value's inorder position in a hash map and reads postorder from the back, building the right subtree before the left, for O(n) time and O(n) space. It requires every value to be distinct.
By Evin JohnPublished 7 min read
The problem in plain words
You receive two lists describing the same binary tree. One lists its values in inorder (left subtree, node, right subtree) and the other in postorder (left subtree, right subtree, node). No value appears twice. Return the root of the tree they describe. Two empty lists describe an empty tree.
inorder = [1, 3, 4, 5, 6, 9, 11]
postorder = [1, 4, 5, 3, 11, 9, 6]
6
/ \
3 9
/ \ \
1 5 11
/
4Why two traversals and not one? A single traversal is ambiguous: the postorder [2, 1] fits both a root 1 with left child 2 and a root 1 with right child 2. Inorder tells you which side each value sits on; postorder tells you who the root is. Together, with distinct values, they pin down exactly one tree.
The key observation
- The last postorder value is the root. Here, 6.
- In inorder, everything left of the root's position belongs to the left subtree (1, 3, 4, 5) and everything to the right belongs to the right subtree (9, 11).
- The left subtree has 4 values, so the first 4 postorder values (1, 4, 5, 3) are its postorder, and the next 2 (11, 9) are the right subtree's postorder.
- Each half is the same problem, one size smaller. Recurse until a range is empty.
Straightforward version: slices and a search
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def build_slow(inorder, postorder):
if not postorder:
return None
root_val = postorder[-1]
mid = inorder.index(root_val) # O(n) search on every call
node = TreeNode(root_val)
node.left = build_slow(inorder[:mid], postorder[:mid])
node.right = build_slow(inorder[mid + 1:], postorder[mid:-1])
return nodeEvery call searches inorder for the root and copies both halves. On a balanced tree that totals O(n log n); on a chain, each level copies almost everything, which is O(n²). It is a perfectly good first answer to state, then improve.
Linear version: index map and a backwards pointer
Two changes remove the waste. First, build a map from value to inorder index once, so finding the root is O(1). Second, stop slicing: describe each subtree by a range of inorder indexes, and take roots from a single pointer that starts at the end of postorder and moves left by one each time a node is created. Read backwards, postorder is root, then the right subtree, then the left subtree. So after creating a node, build its right child first, then its left child. Build them in the other order and the pointer hands left-subtree roots to the right side.
def build_tree(inorder, postorder):
where = {val: i for i, val in enumerate(inorder)}
next_root = len(postorder) - 1 # read postorder from the back
def build(lo, hi): # the subtree whose inorder is inorder[lo..hi]
nonlocal next_root
if lo > hi:
return None
val = postorder[next_root]
next_root -= 1
node = TreeNode(val)
mid = where[val]
node.right = build(mid + 1, hi) # right first: backwards postorder is root, right, left
node.left = build(lo, mid - 1)
return node
return build(0, len(inorder) - 1)class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function buildTree(inorder, postorder) {
const where = new Map(inorder.map((val, i) => [val, i]));
let nextRoot = postorder.length - 1;
function build(lo, hi) {
if (lo > hi) return null;
const val = postorder[nextRoot--];
const node = new TreeNode(val);
const mid = where.get(val);
node.right = build(mid + 1, hi); // must come before the left subtree
node.left = build(lo, mid - 1);
return node;
}
return build(0, inorder.length - 1);
}Trace the first steps. The pointer reads 6: create 6, whose inorder position 4 splits the range 0..6 into 0..3 and 5..6. Build the right range first. The pointer reads 9 (position 5): its right range is 6..6, where the pointer reads 11. Its left range 5..4 is empty. Back at 6, build the left range 0..3: the pointer reads 3, then 5 for 3's right side, then 4 for 5's left side, and finally 1 for 3's left side. Every value is consumed exactly once.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Slices and linear search | O(n²) worst case, O(n log n) balanced | O(n²) worst case for all the copies |
| Index map and pointer | O(n) | O(n) map plus O(h) recursion |
The recursion depth equals the tree's height, so a tree that is one long chain recurses n times. Python's default limit of about a thousand frames will stop it on large chains; raise the limit or rewrite the build with an explicit stack if that input is possible. Say this before the interviewer does.
Edge cases to test
- Both lists empty: return no tree.
- One value: a single node.
- A left-only chain: inorder and postorder are identical lists.
- A right-only chain: inorder is the reverse of postorder.
- Mismatched input, such as different lengths or values that are not in both lists. Clarify whether you may assume valid input.
Common mistakes
- Building the left subtree first while reading postorder backwards, which attaches the wrong roots everywhere.
- Off-by-one slice bounds for the right half: its postorder is
postorder[mid:-1], excluding the root at the end. - Assuming duplicate values are fine. With repeats the map is ambiguous, and so is the tree.
- Calling
index()inside the recursion and still claiming linear time. - Mixing this up with the preorder variant, where the root is the first value and the pointer moves forward, building left before right.
How to explain it out loud
Fictional example
- Candidate
- Postorder ends with the root, so 6 is the root. In inorder, 6 sits at index 4, so four values are on its left and two on its right.
- Candidate
- That split applies recursively. To make it linear I will map each value to its inorder index and keep one pointer that walks postorder from the end.
- Candidate
- Walking backwards, postorder reads root, right, left, so I have to build each right subtree before the left one, or the pointer gives me the wrong roots.
- Candidate
- Each node is created once with an O(1) lookup: O(n) time, O(n) space for the map. It relies on distinct values.
Related problems
If either traversal is unfamiliar, start with Binary Tree Postorder Traversal and Binary Tree Preorder Traversal; the preorder-and-inorder version of this problem uses the same map with a forward pointer. Another problem that measures a tree by positions rather than values is Maximum Width of Binary Tree. The coding problems hub has the full list.
Practicing with Natively
Index-range problems are where small slips hide. While you practice, Natively can read the two arrays from a screenshot on Mac or Windows, check your split at each step, and explain why the right subtree has to come first. Because it transcribes the mock session, you can replay how you described the recursion and tighten the wording.
Questions people ask
How do you construct a binary tree from inorder and postorder traversal?
The last postorder value is the root. Its position in inorder splits the other values into the left and right subtrees. Recurse on each part; with a value-to-index map and a pointer moving backwards through postorder this takes O(n) time.
Why build the right subtree first?
Read from the end, postorder lists the root, then the right subtree, then the left subtree. A single backwards pointer therefore reaches the right subtree's roots first.
Can you rebuild a tree from postorder alone?
No. Different trees share a postorder; inorder is needed to know which side each value is on. The values must also be distinct.
What is the time complexity of building a tree from inorder and postorder?
O(n) with a hash map of inorder positions, versus O(n squared) in the worst case if you search and slice the arrays at every step.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
