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;
}
相关推荐
自不量力的A同学3 小时前
Solon AI v3.9 正式发布:全能 Skill 爆发
java·网络·人工智能
Liekkas Kono3 小时前
RapidOCR Python 贡献指南
开发语言·python·rapidocr
张张努力变强3 小时前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
万岳科技系统开发3 小时前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
xyq20243 小时前
Matplotlib 绘图线
开发语言
独断万古他化3 小时前
【Spring 原理】Bean 的作用域与生命周期
java·后端·spring
m0_694845573 小时前
tinylisp 是什么?超轻量 Lisp 解释器编译与运行教程
服务器·开发语言·云计算·github·lisp
*小海豚*4 小时前
在linux服务器上DNS正常,但是java应用调用第三方解析域名报错
java·linux·服务器
春日见4 小时前
如何创建一个PR
运维·开发语言·windows·git·docker·容器
C++ 老炮儿的技术栈4 小时前
VS2015 + Qt 实现图形化Hello World(详细步骤)
c语言·开发语言·c++·windows·qt