力扣每日一题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;
    }
};
相关推荐
2401_891482176 小时前
多平台UI框架C++开发
开发语言·c++·算法
88号技师7 小时前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t198751287 小时前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
无敌昊哥战神7 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
x_xbx7 小时前
LeetCode:148. 排序链表
算法·leetcode·链表
Darkwanderor7 小时前
三分算法的简单应用
c++·算法·三分法·三分算法
2401_831920748 小时前
分布式系统安全通信
开发语言·c++·算法
WolfGang0073218 小时前
代码随想录算法训练营 Day17 | 二叉树 part07
算法
温九味闻醉8 小时前
关于腾讯广告算法大赛2025项目分析1 - dataset.py
人工智能·算法·机器学习
炽烈小老头8 小时前
【 每天学习一点算法 2026/03/23】数组中的第K个最大元素
学习·算法·排序算法