C语言 | Leetcode C语言题解之第108题将有序数组转换为二叉搜索树

题目:

题解:

cpp 复制代码
struct TreeNode* helper(int* nums, int left, int right) {
    if (left > right) {
        return NULL;
    }

    // 选择任意一个中间位置数字作为根节点
    int mid = (left + right + rand() % 2) / 2;

    struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    root->val = nums[mid];
    root->left = helper(nums, left, mid - 1);
    root->right = helper(nums, mid + 1, right);
    return root;
}

struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
    return helper(nums, 0, numsSize - 1);
}
相关推荐
OOJO2 小时前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
派大星~课堂3 小时前
【力扣-142. 环形链表2 ✨】Python笔记
python·leetcode·链表
笨笨饿4 小时前
29_Z变换在工程中的实际意义
c语言·开发语言·人工智能·单片机·mcu·算法·机器人
艾为电子4 小时前
【技术帖】让接口不再短命:艾为 C-Shielding™ Type-C智能水汽防护技术解析
c语言·开发语言
会编程的土豆4 小时前
【数据结构与算法】动态规划
数据结构·c++·算法·leetcode·代理模式
6Hzlia6 小时前
【Hot 100 刷题计划】 LeetCode 78. 子集 | C++ 回溯算法题解
c++·算法·leetcode
笨笨饿6 小时前
30_泰勒级数
c语言·stm32·嵌入式硬件·线性代数·机器学习·自动化·概率论
OOJO7 小时前
c++---vector介绍
c语言·开发语言·数据结构·c++·算法·vim·visual studio
爱编码的小八嘎9 小时前
C语言完美演绎6-21
c语言
py有趣10 小时前
力扣热门100题之接雨水
算法·leetcode