leetcode106.从中序与后序遍历序列构造二叉树、leetcode105.从前序与中序遍历序列构造二叉树

leetcode106.从中序与后序遍历序列构造二叉树

给定两个整数数组 inorder 和 postorder ,其中 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、后序数组为0,空节点

2、后序数组最后一个元素为根节点

3、寻找根节点在中序数组位置作切割点

4、切中序数组

5、切后序数组

6、递归处理左区间右区间

c 复制代码
struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize) {
   if(!inorderSize) 
    return NULL;
     struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    if (node == NULL) {
        // 处理内存分配失败
        return NULL;
    }
    node->val=postorder[postorderSize-1];
    int index;
    for (index = 0; index < inorderSize; index++) {
        if(inorder[index] == postorder[postorderSize-1]) {
            break;
        }
    }
    int rightSize=inorderSize-index-1;
    node->left=buildTree(inorder,index,postorder,index);//左闭右开
    node->right=buildTree(inorder+index+1,rightSize,postorder + index, rightSize);
    return node;
}

leetcode105.从前序与中序遍历序列构造二叉树

给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

示例 1:

输入: preorder = 3,9,20,15,7, inorder = 9,3,15,20,7

输出: 3,9,20,null,null,15,7

示例 2:

输入: preorder = -1, inorder = -1

输出: -1

解题思路

1、前序数组为0,空节点

2、前序数组第一个元素为根节点

3、寻找根节点在中序数组位置作切割点

4、切中序数组

5、切前序数组

6、递归处理左区间右区间

c 复制代码
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
    if(!inorderSize) 
    return NULL;
     struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    if (node == NULL) {
        // 处理内存分配失败
        return NULL;
    }
    node->val=preorder[0];
    int index;
    for (index = 0; index < inorderSize; index++) {
        if(inorder[index] == preorder[0]) {
            break;
        }
    }
    int rightSize=inorderSize-index-1;
    node->left=buildTree(preorder+1,index,inorder,index);//左闭右开
    node->right=buildTree(preorder+index+1,rightSize,inorder+index+1,rightSize);
    return node;
}
相关推荐
咩咩啃树皮6 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
灯澜忆梦6 小时前
GO_并发编程---定时器
开发语言·后端·golang
鱟鲥鳚6 小时前
Spring Boot 集成 LangChain4j:从模型调用到 Tool Calling(Demo版)
java·spring boot
-银雾鸢尾-6 小时前
C#中的StringBuilder相关方法
开发语言·c#
-银雾鸢尾-7 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
大模型码小白8 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
腾渊信息科技公司8 小时前
Spring Boot对接MES实战:视觉检测数据自动同步方案
java·人工智能·spring boot·后端·计算机视觉·ai·软件需求
爱笑的源码基地9 小时前
高并发 Redis 缓存门诊HIS系统源码,含财务统计药房进销存
java·程序·门诊系统·诊所系统·云诊所源码
wuqingshun3141599 小时前
TCP超时重传机制是为了解决什么问题?
java
段一凡-华北理工大学9 小时前
向量数据库实战:选型、调优与落地~系列文章12:文本分块策略实战:chunk_size 怎么选?重叠多少?
开发语言·数据库·后端·oracle·rust·工业智能体·高炉智能化