Construct Binary Tree from Inorder and Postorder Traversal

medium

Given two integer arrays inorder and postorder — the inorder and postorder traversals of the same binary tree, where all values are unique — construct and return the binary tree.

The tree is returned in level-order (breadth-first), using null for missing children.

Hints

The last postorder value is the root of the (sub)tree.
Find the root in inorder to split into left and right subtrees.
Consume postorder from the back and build the right subtree before the left.

Common doubts

Reading postorder back-to-front, the elements right before the root belong to the right subtree (postorder is left, right, node).
Root is postorder's last (not preorder's first), and you recurse right-before-left instead of left-before-right.
So the root maps to a single inorder position and the split is unambiguous.

Interview follow-ups

Root is preorder's first; consume preorder front-to-back, left subtree before right.
Only up to ambiguity for single-child nodes — not a unique tree in general.

Fun facts

  • Preorder+inorder and inorder+postorder are mirror algorithms: front vs back pointer, left-first vs right-first.
  • Reversed postorder is exactly 'node, right, left' — a mirrored preorder — which is why the pointer runs backward.

Asked at

AmazonMicrosoftBloomberg
Frequently Sometimes Occasionally
Example 1
Input: inorder = [9, 3, 15, 20, 7], postorder = [9, 15, 7, 20, 3]
Output: [3, 9, 20, null, null, 15, 7]
Root 3 (postorder's last); right subtree rooted at 20, left subtree {9}.
Example 2
Input: inorder = [-1], postorder = [-1]
Output: [-1]
A single node.
Constraints

- 1 <= inorder.length <= 3000 - postorder.length == inorder.length - -3000 <= values <= 3000 - All values are unique - inorder and postorder are traversals of the same tree

Solve this problem →