Given two integer arrays preorder
and inorder
where preorder
is the preorder traversal of a binary tree and inorder
is the inorder traversal of the same tree, construct and return the binary tree.
Example 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
Explanation: The binary tree is constructed as follows:
3
/ \
9 20
/ \
15 7
Complexity Analysis
Time Complexity: O(N)
We visit each node once. The HashMap lookup for the inorder index is O(1).
Space Complexity: O(N)
O(N) for the HashMap and O(H) for the recursion stack, where H is the height of the tree. In the worst case (a skewed tree), H can be N.
Java Solution
class Solution {
private int preorderIndex = 0;
private HashMap<Integer, Integer> inorderMap;
public TreeNode buildTree(int[] preorder, int[] inorder) {
// Build HashMap for O(1) inorder index lookup
inorderMap = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
inorderMap.put(inorder[i], i);
}
return buildTreeHelper(preorder, 0, inorder.length - 1);
}
private TreeNode buildTreeHelper(int[] preorder, int left, int right) {
if (left > right) {
return null; // Base case: empty subtree
}
// Get root value from preorder
int rootVal = preorder[preorderIndex++];
TreeNode root = new TreeNode(rootVal);
// Find root position in inorder
int rootIndex = inorderMap.get(rootVal);
// Build left and right subtrees
root.left = buildTreeHelper(preorder, left, rootIndex - 1);
root.right = buildTreeHelper(preorder, rootIndex + 1, right);
return root;
}
}