力扣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;
}
相关推荐
L_09078 小时前
【C++】高阶数据结构 -- 红黑树
数据结构·c++
A_nanda8 小时前
c# MOdbus rto读写串口,如何不相互影响
算法·c#·多线程
代码雕刻家10 小时前
2.4.蓝桥杯-分巧克力
算法·蓝桥杯
Ulyanov10 小时前
顶层设计——单脉冲雷达仿真器的灵魂蓝图
python·算法·pyside·仿真系统·单脉冲
智者知已应修善业12 小时前
【查找字符最大下标以*符号分割以**结束】2024-12-24
c语言·c++·经验分享·笔记·算法
划破黑暗的第一缕曙光12 小时前
[数据结构]:5.二叉树链式结构的实现1
数据结构
91刘仁德12 小时前
c++类和对象(下)
c语言·jvm·c++·经验分享·笔记·算法
青桔柠薯片12 小时前
数据结构:单向链表,顺序栈和链式栈
数据结构·链表
diediedei12 小时前
模板编译期类型检查
开发语言·c++·算法
阿杰学AI12 小时前
AI核心知识78——大语言模型之CLM(简洁且通俗易懂版)
人工智能·算法·ai·语言模型·rag·clm·语境化语言模型