力扣105:从先序和中序序列构造二叉树

给定两个整数数组 preorderinorder ,其中 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]

代码:

复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
    if(preorderSize<=0||inorderSize<=0) return NULL;
    struct TreeNode *root=(struct TreeNode*)malloc(sizeof(struct TreeNode));
    int index;
    root->val=preorder[0];
    for(index=0;index<inorderSize;index++){
        if(inorder[index]==preorder[0]){
            break;
        }
    }
    root->left=buildTree(preorder+1,index,inorder,index);
    root->right=buildTree(preorder+1+index,preorderSize-1-index,inorder+1+index,inorderSize - index - 1);
    return root;
}
相关推荐
CQ_YM4 分钟前
数据结构之栈
数据结构·算法·
爱学习的梵高先生19 分钟前
C++:基础知识
开发语言·c++·算法
xlq2232226 分钟前
24.map set(下)
数据结构·c++·算法
繁华似锦respect1 小时前
C++ & Linux 中 GDB 调试与内存泄漏检测详解
linux·c语言·开发语言·c++·windows·算法
立志成为大牛的小牛1 小时前
数据结构——五十四、处理冲突的方法——开放定址法(王道408)
数据结构·学习·程序人生·考研·算法
子一!!1 小时前
数据结构===红黑树===
数据结构
代码游侠1 小时前
复习——栈、队列、树、哈希表
linux·数据结构·学习·算法
碧海银沙音频科技研究院2 小时前
基于物奇wq7036与恒玄bes2800智能眼镜设计
arm开发·人工智能·深度学习·算法·分类
小白程序员成长日记2 小时前
2025.12.03 力扣每日一题
算法·leetcode·职场和发展
元亓亓亓2 小时前
LeetCode热题100--20. 有效的括号--简单
linux·算法·leetcode