从中序与后序遍历序列构造二叉树解题思路

题目:

给定两个整数数组 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 保证是树的后序遍历

思路:与从前序与中序遍历序列构造二叉树思路大同小异,只是将前序换成了后序,后序根结点为后序数组最后一个;

代码:

cs 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize) {
    if(inorderSize == 0 || postorderSize == 0){
        return NULL;
    }

    //  存入中序遍历根结点索引
    int indexroot = 0;

    // 根节点赋值(后序遍历最后值为根结点)
    struct TreeNode *root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    root -> val = postorder[postorderSize - 1];

    // 寻找中序遍历中根结点
    while (postorder[postorderSize - 1] != inorder[indexroot]){
        indexroot++;
    }

    // 把左右子树结点作为新的根结点处理
    //传入左子树的中序遍历和后序遍历
    root -> left = buildTree(inorder,indexroot,postorder,indexroot);
    root -> right = buildTree(inorder + indexroot + 1,inorderSize - indexroot - 1,postorder + indexroot,inorderSize - indexroot - 1);
    return root;
}

总结:

主要后序遍历根结点为后序数组最后一位;

相关推荐
㓗冽9 分钟前
60题之内难题分析
开发语言·c++·算法
大江东去浪淘尽千古风流人物11 分钟前
【VLN】VLN仿真与训练三要素 Dataset,Simulators,Benchmarks(2)
深度学习·算法·机器人·概率论·slam
铉铉这波能秀38 分钟前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
蜡笔小马1 小时前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree
唐梓航-求职中1 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
仟濹1 小时前
【算法打卡day3 | 2026-02-08 周日 | 算法: BFS】3_卡码网99_计数孤岛_BFS | 4_卡码网100_最大岛屿的面积DFS
算法·深度优先·宽度优先
Ll13045252981 小时前
Leetcode二叉树part4
算法·leetcode·职场和发展
颜酱1 小时前
二叉树遍历思维实战
javascript·后端·算法
宝贝儿好1 小时前
第二章: 图像处理基本操作
算法
小陈phd1 小时前
多模态大模型学习笔记(二)——机器学习十大经典算法:一张表看懂分类 / 回归 / 聚类 / 降维
学习·算法·机器学习