力扣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;
}
相关推荐
爱敲代码的TOM5 小时前
数据结构总结
数据结构
CoderCodingNo6 小时前
【GESP】C++五级练习题 luogu-P1865 A % B Problem
开发语言·c++·算法
大闲在人6 小时前
7. 供应链与制造过程术语:“周期时间”
算法·供应链管理·智能制造·工业工程
小熳芋6 小时前
443. 压缩字符串-python-双指针
算法
Charlie_lll6 小时前
力扣解题-移动零
后端·算法·leetcode
chaser&upper6 小时前
矩阵革命:在 AtomGit 解码 CANN ops-nn 如何构建 AIGC 的“线性基石”
程序人生·算法
weixin_499771556 小时前
C++中的组合模式
开发语言·c++·算法
iAkuya7 小时前
(leetcode)力扣100 62N皇后问题 (普通回溯(使用set存储),位运算回溯)
算法·leetcode·职场和发展
近津薪荼7 小时前
dfs专题5——(二叉搜索树中第 K 小的元素)
c++·学习·算法·深度优先
xiaoye-duck7 小时前
吃透 C++ STL list:从基础使用到特性对比,解锁链表容器高效用法
c++·算法·stl