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

题目:

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

总结:

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

相关推荐
啦哈拉哈1 小时前
【Python】知识点零碎学习1
数据结构·python·算法
多恩Stone1 小时前
【3DV 进阶-10】Trellis 中的表示 SLat 理解(1)
人工智能·python·算法·3d·aigc
Tandy12356_1 小时前
手写TCP/IP协议栈——ARP超时重新请求
c语言·c++·网络协议·计算机网络
Han.miracle1 小时前
算法--003快乐数
数据结构·算法·快乐数
数据门徒1 小时前
《人工智能现代方法(第4版)》 第4章 复杂环境中的搜索 学习笔记
人工智能·算法
永远都不秃头的程序员(互关)1 小时前
查找算法深入分析与实践:从线性查找到二分查找
数据结构·c++·算法
Sunsets_Red1 小时前
二项式定理
java·c++·python·算法·数学建模·c#
菜鸟‍1 小时前
【论文学习】SAMed-2: 选择性记忆增强的医学任意分割模型
人工智能·学习·算法
业精于勤的牙1 小时前
模拟退火算法
算法·机器学习·模拟退火算法