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);
}
相关推荐
爱吃芹菜炒肉24 分钟前
Chapter 16: Power Management
服务器·c语言·网络·tcp/ip·pcie
im_AMBER2 小时前
Leetcode 160 最小覆盖子串 | 串联所有单词的子串
开发语言·javascript·数据结构·算法·leetcode
Rabitebla2 小时前
【数据结构】动态顺序表实现详解:从原理到接口设计(面试视角)
c语言·开发语言·数据结构·c++·面试·职场和发展
YSF2017_32 小时前
C语言-12-静态库制作
c语言·开发语言
帅小伙―苏3 小时前
力扣483找到字符串中所有字母异位词
算法·leetcode
smj2302_796826524 小时前
解决leetcode第3906题统计网格路径中好整数的数目
python·算法·leetcode
KobeSacre4 小时前
leetcode 树
算法·leetcode·职场和发展
conti1234 小时前
水题记录2.4
c++·笔记·题解
大大杰哥4 小时前
leetcode hot100(1) 哈希
leetcode
✎ ﹏梦醒͜ღ҉繁华落℘5 小时前
Makefile(四)--gcc 和gdb
c语言·gnu·gcc和gdb