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);
}
相关推荐
pusue_the_sun1 小时前
数据结构:二叉树oj练习
c语言·数据结构·算法·二叉树
圣保罗的大教堂3 小时前
leetcode 2348. 全 0 子数组的数目 中等
leetcode
曙曙学编程4 小时前
stm32——GPIO
c语言·c++·stm32·单片机·嵌入式硬件
Tisfy6 小时前
LeetCode 837.新 21 点:动态规划+滑动窗口
数学·算法·leetcode·动态规划·dp·滑动窗口·概率
tkevinjd8 小时前
图论\dp 两题
leetcode·动态规划·图论
XH华10 小时前
C语言第九章字符函数和字符串函数
c语言·开发语言
♞沉寂12 小时前
信号以及共享内存
linux·c语言·开发语言
1白天的黑夜112 小时前
链表-2.两数相加-力扣(LeetCode)
数据结构·leetcode·链表
上海迪士尼3513 小时前
力扣子集问题C++代码
c++·算法·leetcode