Construct Binary Tree from Preorder and Inorder Traversal
Rebuild a binary tree from the order in which its values appear in preorder and in inorder.
A binary tree has been written down twice as a list of its values, once in preorder and once in inorder. Given both lists, preorderinordernull
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, and the node at the top is the root. A child together with everything below it is called a subtree. To write a tree down as a list, we have to pick an order in which to visit its nodes. Such an order is called a traversal.
Two orders matter here. Preorder writes a node first, then its whole left subtree, then its whole right subtree. Inorder writes the left subtree first, then the node, then the right subtree. Both repeat the same rule inside every subtree.
Take the tree of Example 1: 3 at the top, 9 as its left child, and 20 as its right child, with 15 and 7 below 20. Preorder writes 3, then the left subtree, 9, then the right subtree, 20, 15, 7. That gives [3, 9, 20, 15, 7]. Inorder writes the left subtree, 9, then 3, then the right subtree as 15, 20, 7, which gives [9, 3, 15, 20, 7].
Now go the other way. Only the two lists are given, so how do we get the tree back? One list alone is not enough. Preorder [1, 2] fits a tree where 2 is the left child of 1 and also one where 2 is the right child. Together, though, the two lists answer two questions: which value is the root, and which values go to its left and to its right. Look at the picture below.
In the row labelled preorder, the first value is 3. Preorder writes a node before anything below it, so the root comes first. In the row labelled inorder, 3 sits in the middle. Inorder writes the whole left subtree before the root and the whole right subtree after it. So 9, on the left of 3, is the left subtree, and 15, 20, 7, on its right, are the right subtree.
Each part is a smaller tree, and the same two questions work on it. The left part has one value, 9, so it is a single node. For the right part, preorder helps again. After the root 3, preorder lists the left subtree, 9, and then the right subtree, starting with its root. That is 20. In inorder, 20 has 15 on its left and 7 on its right, and the tree on the right of the picture is complete.
So each value of preorder, read in order, is the root of the next subtree to build, and its position in inorder splits that subtree into a left part and a right part. A method that solves a problem by calling itself on smaller parts of it is called recursive, and building a tree out of smaller trees has exactly that shape.
Solution Approach
Turning that idea into code means settling three things: what one call of the method builds, how each call knows which preorder value is its root, and how to find that root in inorder quickly instead of searching for it.
What one call builds
What does one call need to know about its subtree? Only which values belong to it, and in inorder those values always sit side by side. So two positions, lohiinorder[lo..hi]
The call takes its root, finds the root's position midlomid - 1mid + 1hilohinull
Reading the roots from preorder
How does a call know which preorder value is its root? Preorder lists a root, then its whole left subtree, then its whole right subtree. If the calls run in that same order, root first, then the left part, then the right part, they need the preorder values exactly in the order the list gives them.
So one counter, nextnext
The left part must be built before the right part. Built the other way round, the call for 15, 20, 7 would take 9 as its root, a value that is not even in its part.
Finding the root in inorder
The simple way to find midinorderlohi
A HashMapinorderinorder
Java Solution
The method buildTree
- First, fill a
namedHashMap with one loop overinorderIndex , from each value to its position.inorder - Set
, a field of the class shared by all calls, to 0, and callnext for the whole ofbuild(preorder, 0, inorder.length - 1) .inorder - Inside
, returnbuild whennull is greater thanlo .hi - Otherwise, make a new node
fromroot , add one topreorder[next] , and look up the root's positionnext inmid .inorderIndex - Build
with a call forroot.left tolo , thenmid - 1 with a call forroot.right tomid + 1 , and returnhi .root
The class also has a small TreeNodelevelOrdermain
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ConstructBinaryTreeFromPreorderInorder {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
private int next; // index of the next root in preorder
private Map<Integer, Integer> inorderIndex; // value -> its position in inorder
public TreeNode buildTree(int[] preorder, int[] inorder) {
inorderIndex = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
inorderIndex.put(inorder[i], i);
}
next = 0;
return build(preorder, 0, inorder.length - 1);
}
// Build the subtree whose values are inorder[lo..hi].
private TreeNode build(int[] preorder, int lo, int hi) {
if (lo > hi) {
return null; // no values: empty subtree
}
TreeNode root = new TreeNode(preorder[next++]); // preorder lists the root first
int mid = inorderIndex.get(root.val); // inorder: left part | root | right part
root.left = build(preorder, lo, mid - 1);
root.right = build(preorder, mid + 1, hi);
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> level = new ArrayList<>();
level.add(root);
while (!level.isEmpty()) {
List<TreeNode> nextLevel = new ArrayList<>();
for (TreeNode node : level) {
out.add(node == null ? "null" : String.valueOf(node.val));
if (node != null) {
nextLevel.add(node.left);
nextLevel.add(node.right);
}
}
level = nextLevel;
}
while (!out.isEmpty() && out.get(out.size() - 1).equals("null")) {
out.remove(out.size() - 1); // drop trailing nulls
}
return out.toString();
}
public static void main(String[] args) {
var builder = new ConstructBinaryTreeFromPreorderInorder(); // one object for all calls
int[][][] cases = {
{{3, 9, 20, 15, 7}, {9, 3, 15, 20, 7}},
{{-1}, {-1}},
{{1, 2, 3}, {3, 2, 1}},
{{1, 2, 3}, {1, 2, 3}},
{{}, {}}
};
for (int[][] c : cases) {
System.out.println(levelOrder(builder.buildTree(c[0], c[1])));
}
}
}
Running it prints:
[3, 9, 20, null, null, 15, 7]
[-1]
[1, 2, null, 3]
[1, null, 2, null, 3]
[]
Look at the third line, [1, 2, null, 3]null
The fourth line is the mirror image. Inorder [1, 2, 3] puts each root first in its part, so every left part is empty and the tree hangs to the right. On the last line, []hibuildnull
All five lines come from the same object, and that works only because buildTreenextArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
Complexity
The work is one pass over inorderbuild
- Time: O(n), because filling
touches each of the n values once, and each value then becomes a node in exactly one call ofinorderIndex , which does one map lookup. The calls that returnbuild number n + 1 and take one step each.null - Space: O(n). The map holds one entry per value. The calls waiting on each other go as deep as the tree is tall, which is n for a chain like the third line of the output. The tree itself is the answer and is not counted as extra.
With postorder instead of preorder, the root is the last value instead of the first: see