题目:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
解决方法:Runtime: 7 ms
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(null==preorder||null==inorder) return null;
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<inorder.length;i++){
map.put(inorder[i],i);
}
return preToTree(preorder,0,preorder.length-1,inorder,0,inorder.length-1,map);
}
private TreeNode preToTree(int[] preorder, int ps,int pe, int[] inorder, int is,int ie, Map<Integer,Integer> map){
if(ps>pe||is>ie) return null;
TreeNode node =new TreeNode(preorder[ps]);
int index = map.get(preorder[ps]);
node.left = preToTree(preorder,ps+1,ps+index-is,inorder,is,index-1,map);
node.right = preToTree(preorder,ps+index-is+1,pe,inorder,index+1,ie,map);
return node;
}
}
参考: