思路:
前序遍历的第一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分为树的左子树中序遍历结果,右部分为树的右子树中序遍历的结果。
实现:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Map;
import java.util.HashMap;
public class Solution {
private Map<Integer,Integer> indexForInOrders=new HashMap<Integer,Integer>();
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
for(int i=0;i<in.length;i++){
indexForInOrders.put(in[i],i);
}
return reConstructBinaryTree(pre,0,pre.length-1,0);
}
private TreeNode reConstructBinaryTree(int []pre,int preL,int preR,int inL){
if(preL>preR) return null;
TreeNode root=new TreeNode(pre[preL]);
int inIndex=indexForInOrders.get(root.val);
int leftTreeSize=inIndex-inL;
root.left=reConstructBinaryTree(pre,preL+1,preL+leftTreeSize,inL);
root.right=reConstructBinaryTree(pre,preL+leftTreeSize+1,preR,leftTreeSize+inL+1);
return root;
}
}