力扣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;
}
相关推荐
DoraBigHead5 分钟前
小哆啦解题记——映射的背叛
算法
Heartoxx16 分钟前
c语言-指针与一维数组
c语言·开发语言·算法
孤狼warrior36 分钟前
灰色预测模型
人工智能·python·算法·数学建模
京东云开发者36 分钟前
京东零售基于国产芯片的AI引擎技术
算法
chao_7892 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
十盒半价2 小时前
从递归到动态规划:手把手教你玩转算法三剑客
javascript·算法·trae
GEEK零零七2 小时前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode
凌肖战2 小时前
力扣网编程274题:H指数之普通解法(中等)
算法·leetcode
秋说2 小时前
【PTA数据结构 | C语言版】将数组中元素反转存放
c语言·数据结构·算法
WebInfra2 小时前
如何在程序中嵌入有大量字符串的 HashMap
算法·设计模式·架构