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

题目:

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

总结:

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

相关推荐
无极低码2 小时前
ecGlypher新手安装分步指南(标准化流程)
人工智能·算法·自然语言处理·大模型·rag
爱编码的小八嘎2 小时前
C语言完美演绎4-7
c语言
软件算法开发3 小时前
基于海象优化算法的LSTM网络模型(WOA-LSTM)的一维时间序列预测matlab仿真
算法·matlab·lstm·一维时间序列预测·woa-lstm·海象优化
superior tigre3 小时前
22 括号生成
算法·深度优先
炘爚4 小时前
C语言(文件操作)
c语言·开发语言
努力也学不会java4 小时前
【缓存算法】一篇文章带你彻底搞懂面试高频题LRU/LFU
java·数据结构·人工智能·算法·缓存·面试
W.D.小糊涂4 小时前
gpu服务器安装windows+ubuntu24.04双系统
c语言·开发语言·数据库
旖-旎5 小时前
二分查找(x的平方根)(4)
c++·算法·二分查找·力扣·双指针
ECT-OS-JiuHuaShan5 小时前
朱梁万有递归元定理,重构《易经》
算法·重构
智者知已应修善业5 小时前
【51单片机独立按键控制数码管移动反向,2片74CH573/74CH273段和位,按键按下保持原状态】2023-3-25
经验分享·笔记·单片机·嵌入式硬件·算法·51单片机