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);
}
相关推荐
itman30134 分钟前
C语言怎么学?从写程序到玩指针的实操攻略
c语言·指针·结构体·编程学习·资源推荐
摸个小yu1 小时前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表
kang_jin2 小时前
C语言结构体入门:stu定义与成员使用
c语言·教程·编程语言·入门·结构体
skywalker_112 小时前
力扣hot100-5(盛最多水的容器),6(三数之和)
算法·leetcode·职场和发展
生信研究猿3 小时前
leetcode 226.翻转二叉树
算法·leetcode·职场和发展
独小乐3 小时前
012.整体框架适配SDRAM|千篇笔记实现嵌入式全栈/裸机篇
c语言·汇编·笔记·单片机·嵌入式硬件·arm·gnu
XWalnut3 小时前
LeetCode刷题 day9
java·算法·leetcode
6Hzlia3 小时前
【Hot 100 刷题计划】 LeetCode 39. 组合总和 | C++ 回溯算法与 startIndex 剪枝
c++·算法·leetcode
宵时待雨4 小时前
优选算法专题1:双指针
数据结构·c++·笔记·算法·leetcode
We་ct4 小时前
LeetCode 172. 阶乘后的零:从暴力到最优,拆解解题核心
开发语言·前端·javascript·算法·leetcode·typescript