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);
}
相关推荐
Joseph Cooper41 分钟前
Linux HID 子系统实战:从虚拟键盘到 input 事件上报
linux·c语言·计算机外设
啧不应该啊1 小时前
Day1 python与c宏观区别
c语言·开发语言
OneT1me2 小时前
CVE-2026-31431 的C语言版本
c语言·开发语言·安全威胁分析
水蓝烟雨2 小时前
3337. 字符串转换后的长度 II
算法·leetcode
_日拱一卒2 小时前
LeetCode:226翻转二叉树
数据结构·算法·leetcode
踩坑记录2 小时前
leetcode hot100 64. 最小路径和 medium 递归优化
leetcode·深度优先
爱编码的小八嘎3 小时前
C‘语言完美演绎9-11
c语言
样例过了就是过了3 小时前
LeetCode热题100 最长有效括号
c++·算法·leetcode·动态规划
一行代码一行诗++3 小时前
C语言中if的使用
c语言·c++·算法
来生硬件工程师3 小时前
【程序库】 MutiButton 按键库
c语言·笔记·stm32·单片机·mcu·嵌入式实时数据库