前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >剑指offer 重建二叉树

剑指offer 重建二叉树

作者头像
week
发布2018-12-12 10:00:14
2790
发布2018-12-12 10:00:14
举报
文章被收录于专栏:用户画像用户画像

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

代码语言:javascript
复制
package Tree;
public class Solution {
    public static void main(String[] args) {
        //测试
        int[] pre= {1,2,4,7,3,5,6,8};
        int[] in= {4,7,2,1,5,3,8,6};
        TreeNode treeNode=reConstructBinaryTree(pre,in);
        System.out.println(treeNode.toString());
    }

    public static TreeNode reConstructBinaryTree(int [] pre,int [] in) {

        TreeNode treeNode=new TreeNode(pre[0]);
        //获取根节点在中序遍历数组中是位置
        int RootIndex=0;
        for(int i=0;i<in.length;i++) {
            if(in[i]==pre[0]) {
                RootIndex=i;
            }
        }
        //将先序的遍历结果分成两份,一份是左子树,一份是右子树
        int[] preLeft=new int[RootIndex];
        int[] preRight=new int[pre.length-RootIndex-1];
        for(int i=0;i<RootIndex;i++) {
            preLeft[i]=pre[i+1];
        }
        for(int i=0;i<pre.length-RootIndex-1;i++) {
            preRight[i]=pre[RootIndex+1+i];
        }
        //将中序的遍历的结果分为两份,一份是左子树,一份是右子树
        int[] midLeft=new int[RootIndex];
        int[] midRight=new int[in.length-RootIndex-1];
        for(int i=0;i<RootIndex;i++) {
            midLeft[i]=in[i];
        }
        for(int i=0;i<in.length-RootIndex-1;i++) {
            midRight[i]=in[RootIndex+i+1];
        }
        if(in.length>0&pre.length>0) {
            if(preLeft.length>0) {
                treeNode.left=reConstructBinaryTree(preLeft,midLeft);
            }
            if(preRight.length>0) {
                treeNode.right= reConstructBinaryTree(preRight,midRight);
            }
        }
        return treeNode;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年11月12日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档