Java Binary Tree Program · OT82
Build a Binary Tree from Preorder and Inorder in Java
The first value in preorder is the root. Its position in the inorder sequence splits that sequence into the left subtree and the right subtree, and the same rule applies recursively.
Problem Statement
Given the preorder and inorder traversals of a binary tree with unique values, rebuild the tree and return its root.
The program prints the rebuilt tree's postorder traversal to show that it is correct.
Input/Output Examples
pre [8, 3, 1, 6, 4, 7, 10, 14], in [1, 3, 4, 6, 7, 8, 10, 14]Outputpostorder 1 4 7 6 3 14 10 8Explanation: the tree [8, 3, 10, 1, 6, null, 14, null, null, 4, 7].pre [1, 2, 3], in [3, 2, 1]Outputpostorder 3 2 1Explanation: each node is the left child of the previous one.pre [5], in [5]Outputpostorder 5Explanation: just the root.Visual Explanation
- Root 8inorder1 3 4 6 7810 14split around 8
- Left: root 3inorder134 6 7next preorder value
- …recurse on each part
- Right: root 10inorder1014after the left subtree
- Doneoriginal tree
Because preorder lists a whole left subtree before the right subtree, building the left side first consumes exactly the right number of preorder values.
Approaches
Both approaches split the inorder range around each root. One finds the root's position with a map; the other searches for it.
Approach 1: Recursion With a Position Map (Recommended)
Idea: map each value to its inorder index, then build recursively, taking roots from preorder in order.
- Store every inorder value's index in a
HashMap. - Take the next preorder value as the root of the current range.
- Build the left subtree from the part before it, then the right subtree from the part after it.
Time: O(n) · Space: O(n).
Approach 2: Recursion With Linear Search
Idea: the same recursion, but each root's inorder position is found by scanning the current range.
- Take the first preorder value of the range as the root.
- Scan the inorder range for it.
- Recurse on both sides using the size of the left part.
Time: O(n²) · Space: O(n). Worst case for a chain-shaped tree.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Recursion With a Position Map (Recommended)
The map turns each root lookup into O(1), making the whole build linear.
import java.util.HashMap;
import java.util.Map;
public class BuildTreeMap {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
}
// Builds a tree from level-order values, where null means "no child here"
static TreeNode build(Integer... values) {
if (values.length == 0 || values[0] == null) {
return null;
}
TreeNode root = new TreeNode(values[0]);
java.util.Queue<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < values.length) {
TreeNode node = queue.poll();
if (i < values.length && values[i] != null) {
node.left = new TreeNode(values[i]);
queue.add(node.left);
}
i++;
if (i < values.length && values[i] != null) {
node.right = new TreeNode(values[i]);
queue.add(node.right);
}
i++;
}
return root;
}
private static int preIndex;
// The next preorder value is the root; its position in the inorder array splits left from right
static TreeNode buildTree(int[] preorder, int[] inorder) {
Map<Integer, Integer> position = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
position.put(inorder[i], i);
}
preIndex = 0;
return build(preorder, position, 0, inorder.length - 1);
}
private static TreeNode build(int[] pre, Map<Integer, Integer> pos, int lo, int hi) {
if (lo > hi) {
return null;
}
TreeNode root = new TreeNode(pre[preIndex++]);
int mid = pos.get(root.val);
root.left = build(pre, pos, lo, mid - 1); // build left first: preorder is root, left, right
root.right = build(pre, pos, mid + 1, hi);
return root;
}
static String postorder(TreeNode n) {
if (n == null) {
return "";
}
String l = postorder(n.left), r = postorder(n.right);
return (l + " " + r + " " + n.val).trim().replaceAll(" +", " ");
}
public static void main(String[] args) {
int[][][] cases = {
{{8, 3, 1, 6, 4, 7, 10, 14}, {1, 3, 4, 6, 7, 8, 10, 14}},
{{1, 2, 3}, {3, 2, 1}},
{{5}, {5}}};
for (int[][] c : cases) {
TreeNode root = buildTree(c[0], c[1]);
System.out.println("pre " + java.util.Arrays.toString(c[0]) + " -> postorder: " + postorder(root));
}
}
}
pre [8, 3, 1, 6, 4, 7, 10, 14] -> postorder: 1 4 7 6 3 14 10 8 pre [1, 2, 3] -> postorder: 3 2 1 pre [5] -> postorder: 5
Time complexity: O(n) · Space complexity: O(n).
Approach 2: Recursion With Linear Search
Simpler state, but slower on skewed trees.
public class BuildTreeScan {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) { this.val = val; }
}
// Builds a tree from level-order values, where null means "no child here"
static TreeNode build(Integer... values) {
if (values.length == 0 || values[0] == null) {
return null;
}
TreeNode root = new TreeNode(values[0]);
java.util.Queue<TreeNode> queue = new java.util.ArrayDeque<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < values.length) {
TreeNode node = queue.poll();
if (i < values.length && values[i] != null) {
node.left = new TreeNode(values[i]);
queue.add(node.left);
}
i++;
if (i < values.length && values[i] != null) {
node.right = new TreeNode(values[i]);
queue.add(node.right);
}
i++;
}
return root;
}
// Same idea, but the root is found in the inorder range with a linear search: O(n^2) worst case
static TreeNode buildTree(int[] preorder, int[] inorder) {
return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
}
private static TreeNode build(int[] pre, int ps, int pe, int[] in, int is, int ie) {
if (ps > pe) {
return null;
}
TreeNode root = new TreeNode(pre[ps]);
int mid = is;
while (in[mid] != root.val) {
mid++;
}
int leftSize = mid - is;
root.left = build(pre, ps + 1, ps + leftSize, in, is, mid - 1);
root.right = build(pre, ps + leftSize + 1, pe, in, mid + 1, ie);
return root;
}
static String postorder(TreeNode n) {
if (n == null) {
return "";
}
String l = postorder(n.left), r = postorder(n.right);
return (l + " " + r + " " + n.val).trim().replaceAll(" +", " ");
}
public static void main(String[] args) {
int[][][] cases = {
{{8, 3, 1, 6, 4, 7, 10, 14}, {1, 3, 4, 6, 7, 8, 10, 14}},
{{1, 2, 3}, {3, 2, 1}},
{{5}, {5}}};
for (int[][] c : cases) {
TreeNode root = buildTree(c[0], c[1]);
System.out.println("pre " + java.util.Arrays.toString(c[0]) + " -> postorder: " + postorder(root));
}
}
}
pre [8, 3, 1, 6, 4, 7, 10, 14] -> postorder: 1 4 7 6 3 14 10 8 pre [1, 2, 3] -> postorder: 3 2 1 pre [5] -> postorder: 5
Time complexity: O(n²) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Recursion With a Position Map | O(n) | O(n) |
| Recursion With Linear Search | O(n²) | O(n) |
Here n is the number of nodes. With the map, each node is created once with constant work; the scanning version can repeat linear searches for each node.
Interview Tips and Recommended Approach
- Values must be unique; otherwise the root's inorder position is ambiguous.
- Build the left subtree first when consuming preorder values.
- Know the postorder version: take roots from the end of postorder and build the right subtree first.
- Preorder plus postorder is not enough to rebuild a general binary tree uniquely.
Recommended Approach: Recursion With a Position Map
Why: it rebuilds the tree in linear time and makes the role of each traversal explicit.