力扣每日一题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;
    }
};
相关推荐
sewinger13 分钟前
区间合并算法详解
算法
XY.散人16 分钟前
初识算法 · 滑动窗口(1)
算法
huanxiangcoco17 分钟前
152. 乘积最大子数组
python·leetcode
韬. .38 分钟前
树和二叉树知识点大全及相关题目练习【数据结构】
数据结构·学习·算法
Word码43 分钟前
数据结构:栈和队列
c语言·开发语言·数据结构·经验分享·笔记·算法
五花肉村长1 小时前
数据结构-队列
c语言·开发语言·数据结构·算法·visualstudio·编辑器
一线青少年编程教师1 小时前
线性表三——队列queue
数据结构·c++·算法
Neituijunsir1 小时前
2024.09.22 校招 实习 内推 面经
大数据·人工智能·算法·面试·自动驾驶·汽车·求职招聘
希望有朝一日能如愿以偿2 小时前
力扣题解(飞机座位分配概率)
算法·leetcode·职场和发展
Espresso Macchiato2 小时前
Leetcode 3306. Count of Substrings Containing Every Vowel and K Consonants II
leetcode·滑动窗口·leetcode medium·leetcode 3306·leetcode周赛417