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);
}
相关推荐
pursuit_csdn5 小时前
LeetCode 1022. Sum of Root To Leaf Binary Numbers
算法·leetcode·深度优先
踩坑记录6 小时前
leetcode hot100 35. 搜索插入位置 medium 二分查找
leetcode
m0_531237177 小时前
C语言-指针终阶
c语言·开发语言
散峰而望8 小时前
C++ 启程:从历史到实战,揭开命名空间的神秘面纱
c语言·开发语言·数据结构·c++·算法·github·visual studio
水饺编程9 小时前
第4章,[标签 Win32] :TextOut 测试案例3代码改编
c语言·c++·windows·visual studio
-海绵东东-9 小时前
哈希表······················
算法·leetcode·散列表
菜鸡儿齐10 小时前
leetcode-全排列
算法·leetcode·深度优先
不想看见40410 小时前
Maximal Square 基本动态规划:二维--力扣101算法题解笔记
算法·leetcode·动态规划
夏乌_Wx10 小时前
LeetCode 160. 相交链表 | 三种解法吃透核心逻辑(哈希表 + 双指针 + 长度对齐)
leetcode·链表·哈希表
Hag_2010 小时前
LeetCode Hot100 53.最大子数组和
数据结构·算法·leetcode