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);
}
相关推荐
Eward-an3 小时前
LeetCode 1980 题通关指南|3种解法拆解“找唯一未出现二进制串”问题,附Python最优解实现
python·算法·leetcode
程序员酥皮蛋4 小时前
hot 100 第四十题 40.二叉树的层序遍历
数据结构·算法·leetcode
We་ct6 小时前
LeetCode 77. 组合:DFS回溯+剪枝,高效求解组合问题
开发语言·前端·算法·leetcode·typescript·深度优先·剪枝
努力学算法的蒟蒻6 小时前
day105(3.6)——leetcode面试经典150
算法·leetcode·面试
猫猫的小茶馆6 小时前
【Linux 驱动开发】Linux 内核启动过程详解
linux·c语言·arm开发·驱动开发·stm32·单片机·mcu
im_AMBER6 小时前
Leetcode 136 最小栈 | 逆波兰表达式求值
数据结构·学习·算法·leetcode·
识君啊6 小时前
Java字符串算法核心攻略
java·数据结构·算法·leetcode·字符串·
郝学胜-神的一滴6 小时前
力扣86题分隔链表:双链表拆解合并法详解
开发语言·数据结构·算法·leetcode·链表·职场和发展
快快起来写代码6 小时前
【leetcode】容器中水的容量最小/大面积
算法·leetcode·职场和发展
zz34572981136 小时前
C语言基础之蓝桥杯
c语言·算法·蓝桥杯