力扣每日一题106:从中序与后序遍历序列构造二叉树

题目

中等

相关标签

相关企业

给定两个整数数组 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/5

通过次数

380K

提交次数

526.4K

通过率

72.2%

结点结构

cpp 复制代码
/**
 * 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) {}
 * };
 */

方法

先在中序遍历中找到根节点的位置,分割左右子树,然后递归建树。

代码

cpp 复制代码
class Solution {
public:
    TreeNode* trackback(int l1,int r1,int l2,int r2,vector<int> &inorder,vector<int> &postorder)
    {
        if(l2>r2) return NULL;
        int mid=l1;
        while(mid<=r1&&inorder[mid]!=postorder[r2])
            mid++;
        TreeNode *root=new TreeNode(postorder[r2]);
        root->left=trackback(l1,mid-1,l2,l2+mid-l1-1,inorder,postorder);
        root->right=trackback(mid+1,r1,l2+mid-l1,r2-1,inorder,postorder);
        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int n=inorder.size();
        TreeNode *root=trackback(0,n-1,0,n-1,inorder,postorder);
        return root;
    }
};
相关推荐
黎雁·泠崖1 分钟前
二叉树综合拔高:遍历还原与OJ题拓展训练
c语言·数据结构·leetcode
2503_946971864 分钟前
【BruteForce/Pruning】2026年度物理层暴力破解与神经网络剪枝基准索引 (Benchmark Index)
人工智能·神经网络·算法·数据集·剪枝·网络架构·系统运维
R&ain8 分钟前
C++的内联函数
c++·算法
zhmc9 分钟前
常用周期函数的傅里叶级数
人工智能·算法
漫随流水1 小时前
leetcode算法(111.二叉树的最小深度)
数据结构·算法·leetcode·二叉树
零售ERP菜鸟2 小时前
IT价值证明:从“成本中心”到“增长引擎”的确定性度量
大数据·人工智能·职场和发展·创业创新·学习方法·业界资讯
じ☆冷颜〃9 小时前
黎曼几何驱动的算法与系统设计:理论、实践与跨领域应用
笔记·python·深度学习·网络协议·算法·机器学习
数据大魔方9 小时前
【期货量化实战】日内动量策略:顺势而为的短线交易法(Python源码)
开发语言·数据库·python·mysql·算法·github·程序员创富
POLITE39 小时前
Leetcode 23. 合并 K 个升序链表 (Day 12)
算法·leetcode·链表
楚来客9 小时前
AI基础概念之八:Transformer算法通俗解析
人工智能·算法·transformer