二刷终于会啦
class Solution {
HashMap<Integer,Integer> hs = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
for(int i=0;i<inorder.length;i++){
hs.put(inorder[i],i);
}
return build(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
public TreeNode build(int[] preorder, int pl,int pr,int[] inorder,int il,int ir){
if(pl>pr) return null;
TreeNode root = new TreeNode(preorder[pl]);
int index = hs.get(preorder[pl]);
int leftlen = index-il;
root.left = build(preorder,pl+1,pl+leftlen,inorder,il,index-1);
root.right = build(preorder,pl+leftlen+1,pr,inorder,index+1,ir);
return root;
}
}