LeetCode解法汇总106. 从中序与后序遍历序列构造二叉树

目录链接:

力扣编程题-解法汇总_分享+记录-CSDN博客

GitHub同步刷题项目:

https://github.com/September26/java-algorithms

原题链接:

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

描述:

给定两个整数数组 inorderpostorder ,其中 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 <= 3000
  • postorder.length == inorder.length
  • -3000 <= inorder[i], postorder[i] <= 3000
  • inorderpostorder 都由 不同 的值组成
  • postorder 中每一个值都在 inorder
  • inorder 保证是树的中序遍历
  • postorder 保证是树的后序遍历

解题思路:

1.和105题差不多,只不过后序遍历的最后一个数字,一定是根节点。中序遍历中找到这个根节点,就可以分成左右两份,分别对应左子树和右子树。

2.所以我们使用和105题一样的策略,唯一要改的就是传入的区间范围。

代码:

复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
    {
        vector<int> indexMap(6000);
        for (int i = 0; i < inorder.size(); i++)
        {
            indexMap[inorder[i] + 3000] = i;
        }
        TreeNode *node = buildNode(indexMap, postorder, inorder, 0, postorder.size() - 1, 0, inorder.size() - 1);
        return node;
    }

    TreeNode *buildNode(vector<int> &indexMap, vector<int> &postorder, vector<int> &inorder, int postStart, int postEnd, int inStart, int inEnd)
    {
        int expectValue = postorder[postEnd];
        int index = indexMap[expectValue+3000];
        int leftLength = index - inStart;
        int rightLength = inEnd - index;
        TreeNode *root = new TreeNode(expectValue);
        if (leftLength >= 1)
        {
            root->left = buildNode(indexMap, postorder, inorder, postStart, postStart + leftLength - 1, inStart, index - 1);
        }
        if (rightLength >= 1)
        {
            root->right = buildNode(indexMap, postorder, inorder, postEnd - rightLength, postEnd - 1, index + 1, inEnd);
        }
        return root;
    }
};
相关推荐
guozhetao7 分钟前
【ST表、倍增】P7167 [eJOI 2020] Fountain (Day1)
java·c++·python·算法·leetcode·深度优先·图论
吃着火锅x唱着歌10 分钟前
LeetCode 611.有效三角形的个数
算法·leetcode·职场和发展
技术卷15 分钟前
详解力扣高频SQL50题之619. 只出现一次的最大数字【简单】
sql·leetcode·oracle
CHANG_THE_WORLD3 小时前
金字塔降低采样
算法·金字塔采样
不知天地为何吴女士5 小时前
Day32| 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
算法
小坏坏的大世界5 小时前
C++ STL常用容器总结(vector, deque, list, map, set)
c++·算法
励志要当大牛的小白菜8 小时前
ART配对软件使用
开发语言·c++·qt·算法
qq_513970448 小时前
力扣 hot100 Day56
算法·leetcode
PAK向日葵9 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
爱喝矿泉水的猛男11 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展