力扣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;
}
相关推荐
合方圆~小文1 天前
4G定焦球机摄像头综合介绍产品指南
数据结构·数据库·人工智能
老蒋新思维1 天前
反脆弱性设计:创始人IP与AI智能体如何构建愈动荡愈强大的知识商业|创客匠人
人工智能·网络协议·tcp/ip·算法·机器学习·创始人ip·创客匠人
Salt_07281 天前
DAY 36 官方文档的阅读
python·算法·机器学习·github
FMRbpm1 天前
串练习--------535.TinyURL的加密和解密
数据结构·c++·新手入门
明洞日记1 天前
【VTK手册027】VTK 颜色连续映射:vtkColorTransferFunction 深度解析与实战指南
c++·图像处理·算法·vtk·图形渲染
Bruce_kaizy1 天前
c++单调数据结构————单调栈,单调队列
开发语言·数据结构·c++
阿坤带你走近大数据1 天前
Python基础知识-数据结构篇
开发语言·数据结构·python
B_lack0261 天前
西门子PLC结构化编程_线性插值算法功能块
算法·pid·西门子plc·博途·线性插值·开环控制
fufu03111 天前
Linux环境下的C语言编程(四十三)
linux·c语言·算法
dragoooon341 天前
[C++——lesson32.数据结构进阶——「初识哈希」]
数据结构·c++·哈希算法