Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
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.
preorder = [3,9,20,15,7]
, inorder = [9,3,15,20,7]
3
/ \
9 20
/ \
15 7
null
(i.e., the tree is empty).preorder
and inorder
will be the same.preorder
traversal, the nodes are visited in this order: root -> left subtree -> right subtree
.inorder
traversal, the nodes are visited in this order: left subtree -> root -> right subtree
.preorder
array is the root of the tree.inorder
array:
inorder
array.inorder
array represent the left subtree.preorder
and inorder
arrays.Here’s the Java implementation of the solution:
import java.util.HashMap;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
private int preorderIndex;
private HashMap<Integer, Integer> inorderIndexMap;
public TreeNode buildTree(int[] preorder, int[] inorder) {
preorderIndex = 0;
inorderIndexMap = new HashMap<>();
// Build a hashmap to store value -> index relations
for (int i = 0; i < inorder.length; i++) {
inorderIndexMap.put(inorder[i], i);
}
return buildTreeHelper(preorder, 0, inorder.length - 1);
}
private TreeNode buildTreeHelper(int[] preorder, int inorderStart, int inorderEnd) {
// Base case - no elements to construct the tree
if (inorderStart > inorderEnd) {
return null;
}
// The first element in preorder is the root node of the current subtree
int rootVal = preorder[preorderIndex++];
TreeNode root = new TreeNode(rootVal);
// Root splits inorder list into left and right subtrees
int rootIndex = inorderIndexMap.get(rootVal);
// Build left subtree
root.left = buildTreeHelper(preorder, inorderStart, rootIndex - 1);
// Build right subtree
root.right = buildTreeHelper(preorder, rootIndex + 1, inorderEnd);
return root;
}
}
inorderIndexMap
takes O(n) time.inorder
array, resulting in O(n) operations.HashMap
storing the inorder indices is O(n).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?