您的位置:首页 > 职场人生

面试题6:重建二叉树

2017-11-22 20:37 225 查看
题目:根据某二叉树的前序遍历和中序遍历结果,重建该二叉树

思路:前序遍历的第一个数字就是根节点,在中序遍历中找到根节点,根节点左边是左子树节点,根节点右边是右子树节点;这样递归构建

public BinaryTreeNode constructCore(int[] pre,int[] in) {
if(pre==null||in==null||pre.length!=in.length) {
return null;
}
return constructCore(pre,in,0,pre.length-1,0,in.length-1);
}

private BinaryTreeNode constructCore(int[] pre,int[] in,int startPre,int endPre,int startIn,int endIn) {
//根节点是前序遍历第一个元素
BinaryTreeNode root=new BinaryTreeNode(pre[startPre]);
//在中序遍历中找到根节点
int rootIn=startIn;
while(in[rootIn]!=pre[startPre]&&rootIn<endIn) {
rootIn++;
}
int length=rootIn-startIn;
//构建左子树
if(length>0) {
root.left=constructCore(pre,in,startPre+1,startPre+length,startIn,rootIn-1);
}
//构建右子树
if(length<endPre-startPre) {
root.right=constructCore(pre,in,startPre+length+1,endPre,rootIn+1,endIn);
}
//返回根节点
return root;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树