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

题目:

给定两个整数数组 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;
}

总结:

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

相关推荐
君义_noip5 小时前
信息学奥赛一本通 1661:有趣的数列 | 洛谷 P3200 [HNOI2009] 有趣的数列
c++·算法·组合数学·信息学奥赛·csp-s
leaves falling5 小时前
C语言内存函数-
c语言·开发语言
程序员:钧念5 小时前
深度学习与强化学习的区别
人工智能·python·深度学习·算法·transformer·rag
leaves falling5 小时前
c语言-扫雷游戏
c语言·单片机·游戏
英英_6 小时前
MATLAB数值计算基础教程
数据结构·算法·matlab
一起养小猫6 小时前
LeetCode100天Day14-轮转数组与买卖股票最佳时机
算法·leetcode·职场和发展
至为芯7 小时前
IP6537至为芯支持双C口快充输出的45W降压SOC芯片
c语言·开发语言
hele_two7 小时前
快速幂算法
c++·python·算法
l1t7 小时前
利用DeepSeek将python DLX求解数独程序格式化并改成3.x版本
开发语言·python·算法·数独
jllllyuz7 小时前
基于子集模拟的系统与静态可靠性分析及Matlab优化算法实现
算法·matlab·概率论