Construct Binary Tree from Preorder and Inorder Traversal
public class Solution {
//HashMap to locate current root index to split the tree in the inorder array
HashMap<Integer, Integer> idxMap = new HashMap<>();
int[] preorder;
int[] inorder;
int preIdx = 0;
public TreeNode buildTree(int[] preorder, int[] inorder) {
this.preorder = preorder;
this.inorder = inorder;
//corner case
if (preorder.length != inorder.length) return null;
int idx = 0;
for (int val : inorder) {
idxMap.put(val, idx++); //HashMap建立val和idx的套路
}
return helper(0, preorder.length); //这里为什么不用 preorder.length - 1 呢?
}
private TreeNode helper(int start, int end) {
if (start == end) return null;
int curRootVal = preorder[preIdx];
TreeNode curRoot = new TreeNode(curRootVal);
preIdx ++;
int curRootIdx = idxMap.get(curRootVal);
curRoot.left = helper(start, curRootIdx);
curRoot.right = helper(curRootIdx + 1, end);
return curRoot;
}
}
最后更新于
这有帮助吗?