首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >105.从前序与中序遍历序列构造二叉树

105.从前序与中序遍历序列构造二叉树

作者头像
名字是乱打的
发布2021-12-23 18:57:16
发布2021-12-23 18:57:16
2580
举报
文章被收录于专栏:软件工程软件工程

题目:

给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。

思路:

递归: 先序第一个结点是头结点,用此分割中序为左右两个部分,为两个左右子树的中序遍历结果,同时我们就确定了左右子树的长度,以此来去先序集合划分左右子树先序遍历结果

代码:

代码语言:javascript
复制
public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length==0||inorder.length==0){
            return null;
        }

        TreeNode root=new TreeNode(preorder[0]);

        for (int i = 0,len=inorder.length; i <len ; i++) {
            if (root.val==inorder[i]){
                int[] inorderLeft=Arrays.copyOfRange(inorder,0,i);
                int[] preorderLeft= Arrays.copyOfRange(preorder,1,1+inorderLeft.length);
                root.left=buildTree(preorderLeft,inorderLeft);

                int[] inorderRight=Arrays.copyOfRange(inorder,i+1,inorder.length);
                int[] preorderRight=Arrays.copyOfRange(preorder,1+inorderLeft.length,preorder.length);
                root.right=buildTree(preorderRight,inorderRight);
                break;
            }
        }
        return root;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/10/18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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