面试题6:重建二叉树

来源:互联网 发布:php pack 转换c 编辑:程序博客网 时间:2024/06/04 00:30

题目:根据某二叉树的前序遍历和中序遍历结果,重建该二叉树

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

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;}




原创粉丝点击