力扣每日一题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;
    }
};
相关推荐
luckys.one21 分钟前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
~|Bernard|2 小时前
在 PyCharm 里怎么“点鼠标”完成指令同样的运行操作
算法·conda
战术摸鱼大师2 小时前
电机控制(四)-级联PID控制器与参数整定(MATLAB&Simulink)
算法·matlab·运动控制·电机控制
Christo32 小时前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
好家伙VCC3 小时前
数学建模模型 全网最全 数学建模常见算法汇总 含代码分析讲解
大数据·嵌入式硬件·算法·数学建模
liulilittle4 小时前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
bkspiderx6 小时前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
中华小当家呐7 小时前
算法之常见八大排序
数据结构·算法·排序算法
沐怡旸8 小时前
【算法--链表】114.二叉树展开为链表--通俗讲解
算法·面试