有二叉树的前序遍历和后序遍历,构造二叉树
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer> ();
for(int i=0;i<inorder.length;i++){
map.put(inorder[i], i);
}
return build(map,preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
private static TreeNode build(HashMap<Integer,Integer> map, int[] preorder,int ps,int pe,int[] inorder,int is,int ie) {
if(ps>pe) return null;
TreeNode root=new TreeNode(preorder[ps]);
if(ps==pe) return root;
int i=map.get(preorder[ps]);
int leftlength=i-is;
root.left=build(map,preorder,ps+1,ps+leftlength,inorder,is,i-1);
root.right=build(map,preorder,ps+i+1-is,pe,inorder,i+1,ie);
return root;
}
}