前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >根据一棵树的中序遍历与后序遍历构造二叉树。

根据一棵树的中序遍历与后序遍历构造二叉树。

作者头像
小雨的分享社区
发布2022-10-26 15:02:27
2470
发布2022-10-26 15:02:27
举报
文章被收录于专栏:小雨的CSDN

题目要求

根据一棵树的中序遍历与后序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。

例如,给出

代码语言:javascript
复制
//中序遍历 inorder = [9,3,15,20,7]
//后序遍历 postorder = [9,15,7,20,3]
//返回如下的二叉树:

//    3
//   / \
//  9  20
//    /  \
//   15   7

代码

代码语言:javascript
复制
    private int index2;
    public TreeNode buildTree(int[] preorder, int[] postorder) {
        index2 = 0;
        //先逆置
        int length = postorder.length;
        for (int i = 0; i < length / 2; i++) {
            int temp = postorder[i];
            postorder[i] = postorder[length - 1 - i];
            postorder[length - 1 - i] = temp;
        }
        return buildTreeHelper(preorder,postorder,0,postorder.length);
    }

    private TreeNode buildTreeHelper(int[] preorder, int[] postorder, int left, int right) {
        if (left >= right){
            //中序遍历结果为空,这个数就是空树
            return null;
        }
        if (index2 >= preorder.length){
            return null;
        }
        TreeNode root = new TreeNode((char) preorder[index2]);
        index2++;
        int pos = find(postorder,left,right,root.val);
        root.right = buildTreeHelper(preorder,postorder,pos+1,right);
        root.left = buildTreeHelper(preorder,postorder,left,pos);

        //一个树的先序遍历的镜像和后序遍历的逆置相同,,,,根右左
        //所以先逆置后序遍历,再调整左右根的打印位置

        return root;
    }

    private int find(int[] inorder, int left, int right, int toFind) {
        for (int i = left; i < right; i++){
            if (inorder[i] == toFind){
                return i;
            }
        }
        return -1;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-01-27,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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