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);
}
相关推荐
夏乌_Wx6 小时前
练题100天——DAY23:存在重复元素Ⅰ Ⅱ+两数之和
数据结构·算法·leetcode
龚礼鹏8 小时前
Android应用程序 c/c++ 崩溃排查流程
c语言·开发语言·c++
ada7_12 小时前
LeetCode(python)108.将有序数组转换为二叉搜索树
数据结构·python·算法·leetcode
独自破碎E12 小时前
加油站环路问题
java·开发语言·算法·leetcode
Swift社区12 小时前
LeetCode 445 - 两数相加 II
算法·leetcode·职场和发展
墨染点香12 小时前
LeetCode 刷题【187. 重复的DNA序列】
算法·leetcode·职场和发展
路弥行至13 小时前
FreeRTOS任务管理详解中: FreeRTOS任务创建与删除实战教程(动态方法)
c语言·开发语言·笔记·stm32·操作系统·freertos·入门教程
了一梨14 小时前
外设与接口:input子系统
linux·c语言
2401_8414956414 小时前
【LeetCode刷题】最大子数组和
数据结构·python·算法·leetcode·动态规划·最大值·最大子数组和