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);
}
相关推荐
文丑颜不良啊5 小时前
LeetCode3001~3020题目解析
java·leetcode
Zwawa6 小时前
陀螺仪数据为什么看起来总在动:零偏、噪声和零漂
c语言·单片机·嵌入式
soso19689 小时前
低功耗设计与BMS开发指南
c语言·开发语言·汇编
老师我太想进步了20269 小时前
【数据结构-8】栈的实现
c语言·数据结构·算法
LCG元10 小时前
串口乱码,先算波特率误差再动代码
c语言·嵌入式
Pniubi12 小时前
力扣19 . 删除表的倒数第N个节点(栈)
算法·leetcode·职场和发展
文丑颜不良啊1 天前
LeetCode2761~2780题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2841~2860题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2921~2940题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2901~2920题目解析
java·leetcode