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);
}
相关推荐
小曹要微笑1 小时前
STM32各系列时钟树详解
c语言·stm32·单片机·嵌入式硬件·算法
inputA2 小时前
【LwIP源码学习8】netbuf源码分析
android·c语言·笔记·嵌入式硬件·学习
前进的李工2 小时前
LeetCode hot100:094 二叉树的中序遍历:从递归到迭代的完整指南
python·算法·leetcode·链表·二叉树
吃着火锅x唱着歌4 小时前
LeetCode 面试题 16.24.数对和
算法·leetcode·职场和发展
Dream it possible!4 小时前
LeetCode 面试经典 150_二叉树层次遍历_二叉树的层平均值(82_637_C++_简单)
c++·leetcode·面试·二叉树
Wenhao.4 小时前
LeetCode Hot100 每日温度
数据结构·算法·leetcode·golang
吃着火锅x唱着歌4 小时前
LeetCode 1679.K和数对的最大数目
算法·leetcode·职场和发展
im_AMBER4 小时前
Leetcode 57
笔记·学习·算法·leetcode
im_AMBER4 小时前
Leetcode 58 | 附:滑动窗口题单
笔记·学习·算法·leetcode
sin_hielo4 小时前
leetcode 2154
算法·leetcode