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);
}
相关推荐
什巳1 小时前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode
麻瓜老宋3 小时前
AI开发C语言应用按步走,表达式计算器calc的第一步,中缀表达式词法分析
c语言·开发语言·atomcode
什巳4 小时前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
一个初入编程的小白4 小时前
C语言:函数栈帧与销毁
c语言·开发语言
smj2302_796826524 小时前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode
ComputerInBook6 小时前
c 和 c++ 中的宏块(macro)
c语言·c++··宏块·宏指令
bu_shuo7 小时前
c与cpp中的argc和argv
c语言·c++·算法
Aurorar0rua8 小时前
CS50 x 2024 Notes Algorithms - 02
c语言·开发语言·学习方法
CoderYanger8 小时前
A.每日一题:3020. 子集中元素的最大数量
java·程序人生·算法·leetcode·面试·职场和发展·学习方法
足球中国8 小时前
nuget把缓存搬离C盘
c语言·windows·缓存