Construct Binary Tree from Inorder and Postorder Traversal
Rebuild a binary tree from the two lists of values that its inorder and postorder walks produce.
A binary tree whose values are all different was walked in two orders, inorder and postorder, and each walk wrote its values into an array. Given the two arrays, inorderpostordernull
Example 1
Output: [3, 9, 20, null, null, 15, 7]
Example 2
Output: [-1]
The Idea
A binary tree is made of nodes. Each node holds a value and has at most two children, a left one and a right one. The node at the top is the root, and a node together with everything below it is called a subtree. To write a tree down as a flat list, you visit its nodes in a fixed order, and such a walk is called a traversal.
This problem uses two traversals. Inorder writes a node's left subtree, then the node, then its right subtree. Postorder writes the left subtree, then the right subtree, and the node itself last, after everything below it. For the tree in Example 1, inorder gives 9, 3, 15, 20, 7 and postorder gives 9, 15, 7, 20, 3.
Either array on its own could come from many different trees. So what does each one tell us, and how do the two fit together? Look at the picture below.
In the row labelled postorder, the last value, 3, is the root of the whole tree, because postorder writes each node after everything below it. That names the root, but not which values hang to its left. The row labelled inorder answers that: inorder writes the left subtree before the root and the right subtree after it. So 9, left of 3, is the left subtree, and 15, 20, 7, right of 3, form the right subtree.
Now look at the braces under the postorder row. The left subtree's one value, 9, comes first, then the right subtree's values 15, 7, 20, then the root. And 15, 7, 20 is itself the postorder of the right subtree, so its last value, 20, is that subtree's root. Finding 20 in inorder splits 15 from 7 in the same way.
So the last postorder value is a root, and its place in inorder splits the other values into a left subtree and a right subtree. Each subtree is a smaller copy of the same problem, solved the same way. A method that solves a problem by calling itself on smaller parts is called recursive.
Solution Approach
Turning that idea into code means settling three things: how a call knows which values belong to its subtree, how to find a root's place in inorder without scanning, and which subtree to build first.
Describing a subtree
What does each recursive call need to know? A subtree's values sit side by side in inorder, so two positions, lohilohinull
Finding a root in inorder
How do we find where 3 sits in inorder? Scanning inorderHashMap
Building the right subtree first
Which value is the next root? Postorder reads left subtree, right subtree, root. Read from the end, that becomes root, right subtree, left subtree. So a single position, nextpostordernextnext
Java Solution
The method buildTreebuild
- First,
fillsbuildTree , ainorderIndex from each value inHashMap to its position.inorder - It sets
tonext , the last position, and callspostorder.length - 1 withbuild = 0 andlo =hi , the whole ofinorder.length - 1 .inorder - In
, an empty range,build , returnslo > hi .null - Otherwise,
makes a new node,build , fromroot , and movespostorder[next] one step left. It looks up the root's position innext and keeps it ininorder .mid - It builds
from the rangeroot.right tomid + 1 , thenhi fromroot.left tolo , and returnsmid - 1 .root
A small TreeNodelevelOrdermain
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ConstructBinaryTreeFromInorderPostorder {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
private int next; // position of the next root in postorder
private Map<Integer, Integer> inorderIndex; // value -> its position in inorder
public TreeNode buildTree(int[] inorder, int[] postorder) {
inorderIndex = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
inorderIndex.put(inorder[i], i);
}
next = postorder.length - 1;
return build(postorder, 0, inorder.length - 1);
}
private TreeNode build(int[] postorder, int lo, int hi) {
if (lo > hi) {
return null; // empty range: no child here
}
TreeNode root = new TreeNode(postorder[next--]); // postorder lists the root last
int mid = inorderIndex.get(root.val);
root.right = build(postorder, mid + 1, hi); // from the end: right part comes first
root.left = build(postorder, lo, mid - 1);
return root;
}
// Prints the tree level by level, with null for a missing child, like the examples.
static String levelOrder(TreeNode root) {
List<String> out = new ArrayList<>();
List<TreeNode> order = new ArrayList<>();
order.add(root);
for (int i = 0; i < order.size(); i++) {
TreeNode node = order.get(i);
out.add(node == null ? "null" : String.valueOf(node.val));
if (node != null) {
order.add(node.left);
order.add(node.right);
}
}
while (!out.isEmpty() && out.get(out.size() - 1).equals("null")) {
out.remove(out.size() - 1);
}
return out.toString();
}
static void run(int[] inorder, int[] postorder) {
var builder = new ConstructBinaryTreeFromInorderPostorder();
System.out.println(levelOrder(builder.buildTree(inorder, postorder)));
}
public static void main(String[] args) {
run(new int[] {9, 3, 15, 20, 7}, new int[] {9, 15, 7, 20, 3});
run(new int[] {-1}, new int[] {-1});
run(new int[] {1, 2, 3}, new int[] {1, 2, 3}); // every node is a left child
run(new int[] {1, 2, 3}, new int[] {3, 2, 1}); // every node is a right child
run(new int[] {4, 2, 5, 1, 6, 3, 7}, new int[] {4, 5, 2, 6, 7, 3, 1});
}
}
Running it prints:
[3, 9, 20, null, null, 15, 7]
[-1]
[3, 2, null, 1]
[1, null, 2, null, 3]
[1, 2, 3, 4, 5, 6, 7]
Look at the first line, [3, 9, 20, null, null, 15, 7]null
The third line comes from inorder [1, 2, 3] and postorder [1, 2, 3]. Postorder ends with 3, and in inorder every other value sits left of 3, so 3 has only a left child, 2, and 2 has only a left child, 1. The fourth line is the mirror image: postorder ends with 1, everything else sits right of 1 in inorder, and the tree leans right. The last line rebuilds a tree whose three levels are all full.
The order of the two recursive calls matters. With root.leftnextnextpostorderArrayIndexOutOfBoundsException
Complexity
The work is one pass to fill the map, plus one call of build
- Time: O(n), for n values. Filling
reads each value ofinorderIndex once. Theninorder makes one node per value, with one map lookup each, and the n + 1 calls that find an empty range return at once.build - Space: O(n). The map holds all n values with their positions. The recursion goes as deep as the tree is tall, which is n for a chain like the third line of the output. The new tree itself is the output.
When preorder is given instead of postorder, the root comes first and the left subtree is built first: see