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);
}
相关推荐
小欣加油12 小时前
leetcode 174 地下城游戏
c++·算法·leetcode·职场和发展·动态规划
菜鸟江多多13 小时前
【STM32 Rocket-Pi原理图分享】
c语言·stm32·嵌入式硬件·mcu·智能硬件·原理图
良木生香13 小时前
【C语言进阶】文件操作的相关详解(1):
c语言·数据结构·c++
你怎么知道我是队长13 小时前
C语言---递归
c语言·开发语言
项目題供诗14 小时前
C语言基础(五)
c语言·开发语言
l1t14 小时前
数独优化求解C库tdoku-lib的使用
c语言·开发语言·python·算法·数独
有一个好名字14 小时前
力扣-奇偶链表
算法·leetcode·链表
wxm63114 小时前
力扣算法题(C++):1、2
java·算法·leetcode
im_AMBER14 小时前
Leetcode 103 反转链表 II
数据结构·c++·笔记·学习·算法·leetcode
iYun在学C14 小时前
驱动程序(创建设备节点实验)
linux·c语言·嵌入式硬件