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

题目:

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

总结:

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

相关推荐
YGGP3 小时前
【Golang】LeetCode 64. 最小路径和
算法·leetcode
意趣新3 小时前
C 语言源文件从编写完成到最终生成可执行文件的完整、详细过程
c语言·开发语言
古城小栈4 小时前
Rust变量设计核心:默认不可变与mut显式可变的深层逻辑
算法·rust
电商API&Tina5 小时前
跨境电商 API 对接指南:亚马逊 + 速卖通接口调用全流程
大数据·服务器·数据库·python·算法·json·图搜索算法
LYFlied5 小时前
【每日算法】LeetCode 1143. 最长公共子序列
前端·算法·leetcode·职场和发展·动态规划
lengjingzju6 小时前
一网打尽Linux IPC(三):System V IPC
linux·服务器·c语言
长安er6 小时前
LeetCode 20/155/394/739/84/42/单调栈核心原理与经典题型全解析
数据结构·算法·leetcode·动态规划·
MarkHD6 小时前
智能体在车联网中的应用:第28天 深度强化学习实战:从原理到实现——掌握近端策略优化(PPO)算法
算法
能源系统预测和优化研究7 小时前
【原创代码改进】考虑共享储能接入的工业园区多类型负荷需求响应经济运行研究
大数据·算法
yoke菜籽7 小时前
LeetCode——三指针
算法·leetcode·职场和发展