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);
}
相关推荐
find1star3 小时前
LeetCode 141:环形链表
java·算法·leetcode·链表
LB21123 小时前
力扣160 21 86
算法·leetcode·职场和发展
a187927218314 小时前
【算法】动态规划第二篇:双序列 DP 三课——继承、计步与断链
算法·leetcode·动态规划·dp·回溯·暴力·算法讲解
Nil20810 小时前
leetcode 994腐烂的橘子
算法·leetcode·职场和发展
热心网友俣先生12 小时前
2026国赛C题:五年命题规律与预测
java·c语言·前端·数学建模
wuminyu13 小时前
Linux内核线程调度与虚拟线程调度机制系统级深度剖析
java·linux·c语言·jvm·c++
血小板要健康13 小时前
队列 + 宽搜(BFS):二叉树层序遍历 算法总结
java·数据结构·笔记·算法·leetcode·宽度优先
不会就选b14 小时前
算法日常・每日刷题--<贪心>3
数据结构·算法·leetcode
ysu_031414 小时前
03-双链表与循环链表
c语言·数据结构·链表
学习星球14 小时前
编辑距离——二维 DP 的“最小操作“艺术
c++·leetcode·java-consul