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);
}
相关推荐
zfxwasaboy3 小时前
DRM KMS 子系统(4)Planes/Encoder/Connector
linux·c语言
夏鹏今天学习了吗3 小时前
【LeetCode热题100(83/100)】最长递增子序列
算法·leetcode·职场和发展
极客代码4 小时前
深入解析C语言中的函数指针:原理、规则与实践
c语言·开发语言·指针·状态机·函数·函数指针
敲皮裤的代码4 小时前
《C语言》分支和循环(下)
c语言
AlenTech5 小时前
155. 最小栈 - 力扣(LeetCode)
算法·leetcode·职场和发展
喵了meme6 小时前
c语言经验分享
c语言·开发语言
坚持不懈的大白6 小时前
Leetcode学习笔记
笔记·学习·leetcode
Tisfy7 小时前
LeetCode 3047.求交集区域内的最大正方形面积:2层循环暴力枚举
算法·leetcode·题解·模拟·枚举·几何
Frank Castle8 小时前
【C语言】详解C语言字节打包:运算符优先级、按位或与字节序那些坑
c语言·开发语言
ltqshs8 小时前
vscode离线插件下载-vscode编译嵌入式C语言配置
c语言·ide·vscode