class Solution {
HashMap<Integer, Integer> inorderValMapIdx = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
for (int i = 0; i < inorder.length; i++) {
inorderValMapIdx.put(inorder[i], i);
}
return buildTree(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
}
// pre: 3 9 20 15 7
// T L R
// in : 9 3 15 20 7
// L T R
public TreeNode buildTree(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) {
if (preStart > preEnd) {
return null;
}
int rootVal = preorder[preStart];
int inorderRootIdx = inorderValMapIdx.get(rootVal);
TreeNode root = new TreeNode(rootVal);
root.left = buildTree(preorder, inorder, preStart + 1, preStart + inorderRootIdx - inStart, inStart, inorderRootIdx - 1);
root.right = buildTree(preorder, inorder, preStart + inorderRootIdx - inStart + 1, preEnd, inorderRootIdx + 1, inEnd);
return root;
}
}
|