LeetCode #106 Medium

Construct BT from Postorder and Inorder

Construct Binary Tree from Inorder and Postorder Traversal is LeetCode 106 (Medium). Given the inorder and postorder traversals of one binary tree, return the root of the tree they describe.

  • inorder visits the left subtree first, the node in the middle, and the right subtree last.
  • postorder visits both subtrees, left before right, and the node last.
  • All values are distinct, so every value identifies one node.

Up to 3,000 values are given, and the target is an O(n) build.

Constraints
  • 1 <= inorder.length <= 3000
  • postorder.length == inorder.length
  • -3000 <= inorder[i], postorder[i] <= 3000
  • inorder and postorder consist of unique values.
  • Each value of postorder also appears in inorder.
  • inorder is guaranteed to be the inorder traversal of the tree.
  • postorder is guaranteed to be the postorder traversal of the tree.
treedivide-and-conquerhash-table
Open on LeetCode ↗
02

Intuition

Postorder writes a node after both of its subtrees, so the last value is the root of the whole tree. Read the array from the back and the order becomes: a root, then its entire right subtree, then its entire left subtree.

Inorder supplies the split: values left of the root form its left subtree, values right of it its right subtree.

So read postorder backwards with one shared index. Each value read is the root of the inorder stretch the current call owns. Since the right subtree comes next in that backwards order, each call builds its right child before its left child; that way the next value read always lands on the side it belongs to.

How to spot this pattern

If a traversal writes each node after its children, read it from the end: roots come out first, and the problem turns into the root-first version with left and right swapped.

03

Approach

Try it first

Before reading on, take inorder [4, 2, 5, 1, 3, 6] and postorder [4, 5, 2, 6, 3, 1]. Read postorder from the right, and for each value say which stretch of inorder it splits. Which subtree is finished first?

1

Map each value to its inorder position

Store pos[value] = index in inorder before building anything. Splitting a stretch around its root then costs one lookup instead of a scan through the array.

2

Point the shared index at the end of postorder

Set p = n - 1. The last value in postorder is the root of the whole tree, and each step of p to the left reaches the next root to place.

3

Build the stretch lo..hi

If lo > hi, the stretch is empty, so return nothing. Otherwise make a node from postorder[p], move p one step left, and look up the node's position mid in inorder.

4

Right child first, then left child

Build the right child from positions mid + 1 to hi first, and the left child from lo to mid - 1 after it. Read backwards, postorder lists a node's right subtree straight after the node, so those are the values p reaches next.

5

Return the root

build(0, n - 1) creates the node for the last postorder value and, through the calls it makes, every node below it. Return that node.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
▶3 pos = {v: k for k, v in enumerate(inorder)}
▶4 p = len(postorder) - 1
▶5 
▶6 def build(lo, hi):
▶7 nonlocal p
▶8 if lo > hi:
▶9 return None
▶10 node = TreeNode(postorder[p])
▶11 p -= 1
▶12 mid = pos[node.val]
▶13 node.right = build(mid + 1, hi)
▶14 node.left = build(lo, mid - 1)
▶15 return node
▶16 
▶17 return build(0, len(inorder) - 1)
postorderinorder452631p425136p starts at the last value, 1
p5
stretch0..5
Postorder ends with the root, so the pointer p starts at the back and moves left. The whole inorder row (outlined) is the stretch the first call must build. Each node will be drawn straight above its own inorder position.
postorderinorder452631p4251361last value, 1, is the root
node1
mid3
stretch0..5
1 is the next value from the back of postorder, so it is the root of the outlined stretch. It sits at inorder position 3: 3, 6 to its right, 4, 2, 5 to its left. The right side is built first, because the values just before 1 in postorder are its right subtree.
postorderinorder452631p425136133 is next from the back → right child of 1
node3
mid4
stretch4..5
3 is the next value from the back of postorder, so it is the root of the outlined stretch and the right child of 1. It sits at inorder position 4: 6 to its right, nothing to its left. The right side is built first, because the values just before 3 in postorder are its right subtree.
postorderinorder452631p4251361366 is next from the back → right child of 3
node6
mid5
stretch5..5
6 is the next value from the back of postorder, so it is the root of the outlined stretch and the right child of 3. It sits at inorder position 5: nothing to its right, nothing to its left. The right side is built first, because the values just before 6 in postorder are its right subtree.
postorderinorder452631p425136136nothing right of 6 → empty
stretchempty
p2
Inside its stretch, inorder has no values on the right of 6, so that subtree is empty. Return nothing and leave p alone: 2 belongs to the left side or an ancestor.
postorderinorder452631p425136136nothing left of 6 → empty
stretchempty
p2
Inside its stretch, inorder has no values on the left of 6, so that subtree is empty. Return nothing and leave p alone: 2 belongs to an ancestor.
postorderinorder452631p425136136nothing left of 3 → empty
stretchempty
p2
Inside its stretch, inorder has no values on the left of 3, so that subtree is empty. Return nothing and leave p alone: 2 belongs to an ancestor.
postorderinorder452631p42513613622 is next from the back → left child of 1
node2
mid1
stretch0..2
2 is the next value from the back of postorder, so it is the root of the outlined stretch and the left child of 1. It sits at inorder position 1: 5 to its right, 4 to its left. The right side is built first, because the values just before 2 in postorder are its right subtree.
postorderinorder452631p425136136255 is next from the back → right child of 2
node5
mid2
stretch2..2
5 is the next value from the back of postorder, so it is the root of the outlined stretch and the right child of 2. It sits at inorder position 2: nothing to its right, nothing to its left. The right side is built first, because the values just before 5 in postorder are its right subtree.
postorderinorder452631p42513613625nothing right of 5 → empty
stretchempty
p0
Inside its stretch, inorder has no values on the right of 5, so that subtree is empty. Return nothing and leave p alone: 4 belongs to the left side or an ancestor.
postorderinorder452631p42513613625nothing left of 5 → empty
stretchempty
p0
Inside its stretch, inorder has no values on the left of 5, so that subtree is empty. Return nothing and leave p alone: 4 belongs to an ancestor.
postorderinorder452631p4251361362544 is next from the back → left child of 2
node4
mid0
stretch0..0
4 is the next value from the back of postorder, so it is the root of the outlined stretch and the left child of 2. It sits at inorder position 0: nothing to its right, nothing to its left. The right side is built first, because the values just before 4 in postorder are its right subtree.
postorderinorder452631p425136136254nothing right of 4 → empty
stretchempty
p-1
Inside its stretch, inorder has no values on the right of 4, so that subtree is empty. Return nothing and leave p alone.
postorderinorder452631p425136136254nothing left of 4 → empty
stretchempty
p-1
Inside its stretch, inorder has no values on the left of 4, so that subtree is empty. Return nothing and leave p alone.
postorderinorder452631p425136136254all 6 values placed → return root 1
root1
p has passed the front of postorder, so every value is placed. Each node sits above its inorder position, and every subtree covers one unbroken stretch of inorder, which is exactly what an inorder listing requires. Return the root, 1.
05

Common pitfalls

Building the left child first

✗ Wrong
node.left = build(lo, mid - 1)
node.right = build(mid + 1, hi)
✓ Right
node.right = build(mid + 1, hi)
node.left = build(lo, mid - 1)

The value p reaches next is the root of the right subtree, and the left call takes it. On inorder [4, 2, 5, 1, 3, 6] and postorder [4, 5, 2, 6, 3, 1], the left side of 1 should hold 4, 2 and 5, but it is handed 3, which belongs on the right, so the tree comes out wrong.

Reading postorder from the front

✗ Wrong
p = 0
...
p += 1
✓ Right
p = len(postorder) - 1
...
p -= 1

The front of postorder is the leftmost leaf, not the root. On the same input the first value read is 4, so a leaf is made the root of the whole tree.

Slicing the right part of postorder one place too far

✗ Wrong
node.right = self.buildTree(inorder[mid + 1:], postorder[mid + 1:])
✓ Right
node.right = self.buildTree(inorder[mid + 1:], postorder[mid:-1])

In postorder the right subtree starts straight after the mid left-subtree values, at index mid, and stops before the root at the end. On the input above mid is 3: the right part should be [6, 3], but postorder[4:] gives [3, 1], which drops 6 and brings the root 1 back in.

06

Edge cases

Every node has only a right child

Inorder is then postorder reversed, such as [1, 2, 3] and [3, 2, 1]. Every left call returns at once, while the right calls nest up to 3,000 deep. Python's default recursion limit is 1,000, so a runner that keeps it needs sys.setrecursionlimit; C++ and Java cope.

07

Complexity

Time
O(n)
Space
O(n)
Every value is read from postorder once and found in the map in one step. The map stores n positions; the recursion adds one frame per level of the tree.
08

Which traversal pair is this?

Both inorder pairs take the split from inorder; what changes is where the roots come from and which side is built first. 889 has no inorder at all.

ProblemWhere the next root isRead orderChildren built
105 Preorder + Inorderfront of preorderfront to backleft, then right
106 Inorder + Postorder (this page)back of postorderback to frontright, then left
889 Preorder + Postorderfront of preorderfront to backleft, then right; unique only if every node has 0 or 2 children
09

Construct BT from Postorder and Inorder FAQ

Can I get the preorder traversal without building the tree?

Yes. Give each call a range in both arrays. The root is the last value of its postorder range, and its inorder position gives the left size k: the first k values of the postorder range are the left subtree, the rest before the root are the right. Output the root, then recurse on the left ranges, then the right.

Is there a version without recursion?

Yes. Walk postorder from the back with a stack of nodes that may still get a left child, and a second pointer walking inorder from the back. Each new value is the right child of the top node, unless the top matches the inorder pointer: then pop while they match, and the new value is the left child of the last node popped. It is O(n) too, and avoids deep recursion on a chain.