栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

leetcode-106. 从中序与后序遍历序列构造二叉树

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode-106. 从中序与后序遍历序列构造二叉树

leetcode-106. 从中序与后序遍历序列构造二叉树

给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树

题目

示例 1:

输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]

示例 2:

输入:inorder = [-1], postorder = [-1]
输出:[-1]

提示:

1 <= inorder.length <= 3000postorder.length == inorder.length-3000 <= inorder[i], postorder[i] <= 3000inorder 和 postorder 都由 不同 的值组成postorder 中每一个值都在 inorder 中inorder 保证是树的中序遍历postorder 保证是树的后序遍历 C++

class Solution {
public:

    TreeNode* func_build_bitree(vector inorder, vector postorder,int s1,int e1,int s2,int e2){
        if (s1 > e1 || s2 > e2) //  空节点
            return NULL;
        int rootVal = postorder[e2]; // 根节点的值
        int rootIndex = 0;  // 根节点在中序遍历中的位置
        for(rootIndex = 0;rootIndex < inorder.size();rootIndex++){    //  在先序序列中找到根节点的位置
            if(inorder[rootIndex] == rootVal)
                break;
        }
        int lLength = rootIndex - s1;   //  左子树长度
        int rLength = e1 - rootIndex;   //  右子树长度
        TreeNode* root = new TreeNode(rootVal);  // 构造根节点
        root->left = func_build_bitree(inorder,postorder,s1,rootIndex - 1,s2,s2 + lLength - 1);
        root->right = func_build_bitree(inorder,postorder,rootIndex + 1,e1,e2 - rLength,e2 - 1);
        return root;
    } 

    TreeNode* buildTree(vector& inorder, vector& postorder) {
        if(inorder.empty() || postorder.empty())
            return NULL;
        TreeNode* root = func_build_bitree(inorder,postorder,0,inorder.size() - 1,0,inorder.size() - 1);
        return root;

    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/738267.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号