您的位置:首页 > 其它

重建二叉树(根据前序和中序遍历结果)

2017-12-18 16:50 295 查看
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        return build(pre,0,pre.length-1,in,0,in.length-1);
    }
    public TreeNode build(int[]preorder,int start1,int end1,int[]inorder,int start2,int end2){
if(start1>end1||start2>end2) return null;
int rootval=preorder[start1]; 	//前序第一个结点为根
System.out.print(rootval+" ");
TreeNode root=new TreeNode(rootval);
int index=indexfindinorder(inorder,start2,end2,rootval);//在中序找到该根节点下标
root.left=build(preorder,start1+1,index+start1,inorder,start2,start2+index-1);//左子树
root.right=build(preorder,index+start1+1,end1,inorder,start2+index+1,end2);//右子树
return root;
}
private int indexfindinorder(int[] inorder, int start, int end,int rootval) {//在中序找到该根节点下标
int count=0;
for(int i=start;i<=end;i++){
if(inorder[i]==rootval)return count;
count++;
}
return -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐