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);
}
相关推荐
Mr_Xuhhh1 小时前
LeetCode hot 100(C++版本)(上)
c++·leetcode·哈希算法
笨笨饿2 小时前
20_Git 仓库使用手册 - 初学者指南
c语言·开发语言·嵌入式硬件·mcu·学习
C++ 老炮儿的技术栈2 小时前
分享一个安全的CString
c语言·c++·windows·git·安全·visual studio
穿条秋裤到处跑3 小时前
每日一道leetcode(2026.03.31):字典序最小的生成字符串
算法·leetcode
爱编码的小八嘎4 小时前
C语言完美演绎6-2
c语言
副露のmagic6 小时前
数组章节 leetcode 思路&实现
算法·leetcode·职场和发展
blueSatchel6 小时前
I2C驱动学习
linux·c语言
爱编码的小八嘎6 小时前
C语言完美演绎6-12
c语言
小Tomkk6 小时前
怎么配置 Visual Studio Code 配置 C/C++
c语言·c++·vscode
Frostnova丶6 小时前
LeetCode 3474. 字典序最小的生成字符串
算法·leetcode·职场和发展