描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
代码
其中(start-inS)表示根据前序序列的根节点,获取中序序列中该根节点的下标start,之后与inS(中序序列的根节点的下标)作差,得到在中序序列中,获取根节点偏移的长度。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int[] pre,in;
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre==null||in==null||pre.length==0||in.length==0){
return null;
}
this.pre=pre;this.in=in;
return construct(0,this.pre.length-1,0,this.in.length-1);
}
public TreeNode construct(int preS,int preE,int inS,int inE){
if(preS>preE||inS>inE){
return null;
}
TreeNode root=new TreeNode(pre[preS]);//头结点
root.left=null;root.right=null;
int start=inS;
for(start=inS;start<=inE;start++){
if(in[start]==pre[preS]){
break;
}
}
root.left=construct(preS+1,preS+(start-inS),inS,start-1);
root.right=construct(preS+(start-inS)+1,preE,start+1,inE);
return root;
}
}