Algo-Sim › Binary Trees & BST
Construct Binary Tree from Preorder and Inorder Traversal
Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input
The next preorder value is the root; its position in inorder splits the remaining values into the left and right subtrees.
Problem
You are given the preorder and inorder traversals of the same binary tree, whose values are all distinct. Rebuild the tree and return its root.
Constraints
- 1 ≤ preorder.length ≤ 3000
- inorder.length = preorder.length
- -3000 ≤ values ≤ 3000, all distinct
- Both arrays describe the same tree
Edge cases to test
- One node
- A left-only chain
- Duplicate values (ambiguous: the task forbids them)
Follow-up questions
- Why a hash map of inorder positions?
- Finding each root in inorder by scanning is O(n), making the build O(n²); a map makes it O(n).
- Can preorder and postorder rebuild a tree?
- Only for full binary trees; otherwise a single child could be left or right (LC 889).
Solution
Java
private int pre = 0;
private Map<Integer, Integer> index = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
for (int i = 0; i < inorder.length; i++) index.put(inorder[i], i);
return build(preorder, 0, inorder.length - 1);
}
private TreeNode build(int[] preorder, int lo, int hi) {
if (lo > hi) return null;
TreeNode root = new TreeNode(preorder[pre++]);
int mid = index.get(root.val);
root.left = build(preorder, lo, mid - 1);
root.right = build(preorder, mid + 1, hi);
return root;
}Python
def build_tree(preorder, inorder):
index = {v: i for i, v in enumerate(inorder)}
pre = 0
def build(lo, hi):
nonlocal pre
if lo > hi:
return None
root = TreeNode(preorder[pre])
pre += 1
mid = index[root.val]
root.left = build(lo, mid - 1)
root.right = build(mid + 1, hi)
return root
return build(0, len(inorder) - 1)C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int pre = 0;
unordered_map<int, int> index = {};
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
for (int i = 0; i < int(inorder.size()); i++)
index[inorder[i]] = i;
return build(preorder, 0, int(inorder.size()) - 1);
}
TreeNode *build(vector<int> &preorder, int lo, int hi) {
if (lo > hi)
return nullptr;
TreeNode *root = new TreeNode(preorder[pre++]);
int mid = index[root->val];
root->left = build(preorder, lo, mid - 1);
root->right = build(preorder, mid + 1, hi);
return root;
}
};
More Binary Trees & BST problems
- Preorder Traversal (Recursive) (Easy)
- Inorder Traversal (Recursive) (Easy)
- Postorder Traversal (Recursive) (Easy)
- Preorder Traversal (Iterative) (Easy)
- Inorder Traversal (Iterative) (Easy)
- Postorder Traversal (Iterative) (Easy)
- Binary Tree Level Order Traversal (Medium)
- Binary Tree Zigzag Level Order Traversal (Medium)
- Binary Tree Right Side View (Medium)
- Vertical Order Traversal of a Binary Tree (Hard)
- Maximum Depth of Binary Tree (Easy)
- Diameter of Binary Tree (Easy)
- Balanced Binary Tree (Easy)
- Invert Binary Tree (Easy)
- Flatten Binary Tree to Linked List (Medium)
- Same Tree (Easy)
- Symmetric Tree (Easy)
- Subtree of Another Tree (Easy)
- Path Sum (Easy)
- Path Sum II (Medium)
- Path Sum III (Medium)
- Count Good Nodes in Binary Tree (Medium)
- Lowest Common Ancestor of a Binary Tree (Medium)
- Kth Ancestor of a Tree Node (Hard)
- All Nodes Distance K in Binary Tree (Medium)
- Validate Binary Search Tree (Medium)
- Search in a Binary Search Tree (Easy)
- Insert into a Binary Search Tree (Medium)
- Delete Node in a BST (Medium)
- Kth Smallest Element in a BST (Medium)
- Binary Search Tree Iterator (Medium)
- Convert Sorted Array to Binary Search Tree (Easy)
- AVL Tree Insert (Hard)
- Binary Tree Maximum Path Sum (Hard)
- Serialize and Deserialize Binary Tree (Hard)