根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int preorder[];
int inorder[];
int count = 0;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
this.preorder = preorder;
this.inorder = inorder;
int i = 0;
for(int x:inorder){
map.put(x,i++);
}
TreeNode head = helper(0,inorder.length);
return head;
}
public TreeNode helper(int left,int right){
if(left==right){
return null;
}
int root_val = preorder[count];
TreeNode root = new TreeNode(root_val);
count++;
int index = map.get(root_val);//分离左右子树的界限
root.left = helper(left,index);
root.right = helper(index+1,right);
return root;
}
}