Construct Binary Tree from Preorder and Inorder Traversal (LeetCode 105): Solution and Explanation
You are given two arrays describing the same binary tree: its preorder traversal and its inorder traversal. All values are unique. Rebuild the original tree and return its root.
Watch it run step by step
Try your own input and write the code →Intuition
Each traversal alone is ambiguous, since many trees share the same preorder or the same inorder sequence. The question is what each one tells you that the other does not. Preorder always lists a node before anything in its subtrees, so the very first element is the root. Inorder lists everything in the left subtree, then the root, then everything in the right subtree, so once you know the root you can find it in inorder and split the array cleanly into left and right parts.
That split also tells you sizes. If the root sits at index mid in inorder, the left subtree has exactly mid nodes. In preorder, after the root comes the entire left subtree and then the entire right subtree, so the next mid elements, preorder[1:mid + 1], are the left subtree's preorder and everything after is the right subtree's preorder.
Now you have two smaller instances of the same problem, each with a matching preorder and inorder pair. Recurse on both, attach the results as the root's children, and stop when an array is empty. This is classic divide and conquer, and the reference solution writes it in the most readable way, with list slicing and inorder.index. That costs extra time on lopsided trees, which a hash map of inorder positions and index bounds can remove.
Approach: Recursive divide and conquer with slicing
- If either array is empty, return None because there is no subtree to build.
- Create the root from
preorder[0], since preorder always starts with the root. - Find
mid = inorder.index(preorder[0]). Everything left ofmidin inorder belongs to the left subtree, and everything right of it belongs to the right subtree. - Build the left child from
preorder[1:mid+1]andinorder[:mid], which both contain exactly themidleft-subtree nodes. - Build the right child from
preorder[mid+1:]andinorder[mid+1:]. - Return the root with both children attached.
Step-by-step example
preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
- The root is 3. It sits at index 1 in inorder, so the left subtree has one node.
- The left call gets preorder [9] and inorder [9]. It makes node 9, and both of its recursive calls receive empty arrays and return None.
- The right call gets preorder [20,15,7] and inorder [15,20,7]. Its root is 20, found at index 1 of that inorder slice.
- Inside that call, the left child is built from [15] and [15], and the right child from [7] and [7].
- The final tree is 3 with left child 9 and right child 20, and 20 has children 15 and 7, which is [3,9,20,null,null,15,7] in level order.
Code: Python, Java, C++
1class Solution:
2 def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
3 if not preorder or not inorder:
4 return None
5
6 root = TreeNode(preorder[0])
7 mid = inorder.index(preorder[0])
8
9 root.left = self.buildTree(preorder[1:mid+1], inorder[:mid])
10 root.right = self.buildTree(preorder[mid+1:], inorder[mid+1:])
11
12 return root1class Solution {
2 public TreeNode buildTree(int[] preorder, int[] inorder) {
3 return helper(0, 0, inorder.length - 1, preorder, inorder);
4 }
5
6 public TreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) {
7 if (preStart > preorder.length - 1 || inStart > inEnd) return null;
8
9 TreeNode root = new TreeNode(preorder[preStart]);
10 int inIndex = 0;
11 for (int i = inStart; i <= inEnd; i++) {
12 if (inorder[i] == root.val) {
13 inIndex = i;
14 }
15 }
16
17 root.left = helper(preStart + 1, inStart, inIndex - 1, preorder, inorder);
18 root.right = helper(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder);
19 return root;
20 }
21}1class Solution {
2public:
3 TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
4 if (preorder.empty() || inorder.empty()) return nullptr;
5
6 TreeNode* root = new TreeNode(preorder[0]);
7 int mid = find(inorder.begin(), inorder.end(), preorder[0]) - inorder.begin();
8
9 vector<int> leftPre(preorder.begin() + 1, preorder.begin() + mid + 1);
10 vector<int> leftIn(inorder.begin(), inorder.begin() + mid);
11 root->left = buildTree(leftPre, leftIn);
12
13 vector<int> rightPre(preorder.begin() + mid + 1, preorder.end());
14 vector<int> rightIn(inorder.begin() + mid + 1, inorder.end());
15 root->right = buildTree(rightPre, rightIn);
16
17 return root;
18 }
19};Time and space complexity
O(n²)
Each call does a linear inorder.index search and copies slices proportional to its subtree size. On a skewed tree those costs add up to n + (n - 1) + (n - 2) and so on, which is quadratic. A balanced tree costs O(n log n).
O(n²)
Every active call on the recursion stack holds its own copied slices. On a skewed tree the stack is n deep with slices of shrinking size, so the worst case is quadratic. Balanced trees need O(n log n).
Other approaches
Hash map of inorder indices with bounds (time O(n), space O(n))
Precompute a map from value to inorder index and recurse with left and right inorder bounds plus a shared pointer into preorder that advances each time a node is created. No slicing and no linear search are needed, so the build is linear.
Iterative build with a stack (time O(n), space O(n))
Walk preorder, pushing nodes as left children until the top of the stack matches the next inorder value, then pop while it matches and attach the next preorder value as a right child. It is linear and avoids recursion but is harder to explain.
Common mistakes
- Slicing preorder as
preorder[1:mid]instead ofpreorder[1:mid+1]. The left subtree hasmidnodes starting at index 1, so the end index ismid + 1. - Recursing on the right subtree before the left in the pointer-based version. Preorder lists the left subtree first, so the shared index must be consumed left first.
- Assuming this works with duplicate values. With duplicates,
inorder.indexcan find the wrong occurrence and the tree is no longer uniquely determined. - Calling this solution O(n). The slicing and linear search make it O(n²) in the worst case.
Frequently asked questions
Why do you need both preorder and inorder to build the tree?
Preorder tells you which node is the root of each subtree, while inorder tells you which nodes fall on the left and which on the right. Neither alone is enough to pin down a unique shape when values are distinct.
How do you make the construction O(n)?
Store each value's inorder index in a hash map so you can find the root position in constant time, and pass index bounds instead of slicing arrays. Then each node is created once with constant work.
Can you build a tree from preorder and postorder?
Not uniquely in general. Without inorder, a node with a single child is ambiguous because you cannot tell whether the child is on the left or the right. It works only when every node has zero or two children.