版权声明:未经允许禁止转载 https://blog.csdn.net/weixin_38481963/article/details/88121609
思路:
根据前序遍历,我们可以知道二叉树的根节点,根据这个跟节点我们可以在中序遍历中找到该节点的位置k,小于k的节点均为该节点的左子树,大于k的节点均为该节点的右子树。
这样的话,我们就很容易想到递归的方式。每次递归都返回该子树的根节点。
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre==null || in==null || pre.length==0 || in.length==0) return null;
return rebuildTree(pre,0,pre.length-1,in,0,in.length-1);
}
public TreeNode rebuildTree(int pre[],int startPre,int endPre,int in[],int startIn,int endIn){
if(startPre>endPre || startIn>endIn){
return null;
}
int rootIndex = getRootIndex(pre[startPre],in,startIn,endIn);
TreeNode root = new TreeNode(pre[startPre]);
root.left = rebuildTree(pre,startPre+1,startPre+rootIndex-startIn,in,startIn,rootIndex-1);
root.right = rebuildTree(pre,startPre+rootIndex-startIn+1,endPre,in,rootIndex+1,endIn);
return root;
}
public int getRootIndex(int target,int in[],int startIn,int endIn){
for(int i=startIn; i<= endIn; i++)
{
if(in[i]==target){
return i;
}
}
return -1;
}
}