LeetCode //C - 108. Convert Sorted Array to Binary Search Tree

本文介绍了如何将已排序的整数数组转换为高度平衡的二叉搜索树(BST),通过递归地分割数组并选择中间元素作为新节点,然后构建左右子树。方法使用了辅助函数和递归策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

108. Convert Sorted Array to Binary Search Tree

Given an integer array nums where the elements are sorted in ascending order, convert it to a height balanced binary search tree.
 

Example 1:

在这里插入图片描述

Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:

在这里插入图片描述

Example 2:

在这里插入图片描述

Input: nums = [1,3]
Output: [3,1]
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.

Constraints:
  • 1 <= nums.length <= 1 0 4 10^4 104
  • - 1 0 4 < = n u m s [ i ] < = 1 0 4 10^4 <= nums[i] <= 10^4 104<=nums[i]<=104
  • nums is sorted in a strictly increasing order.

From: LeetCode
Link: 108. Convert Sorted Array to Binary Search Tree


Solution:

Ideas:
  1. The helper function is used to convert a subarray defined by the start and end indices into a subtree of the BST.
  2. If start > end, it means the subarray is empty and we return NULL.
  3. We calculate the middle index of the subarray and use the element at that index to create a new tree node.
  4. The left and right children of this new node are recursively determined by the left and right halves of the subarray.
  5. The sortedArrayToBST function is just an entry point that calls the helper function using the entire array as the initial subarray.
Code:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* helper(int* nums, int start, int end) {
    if (start > end) {
        return NULL;
    }
    
    int mid = start + (end - start) / 2;
    struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    node->val = nums[mid];
    node->left = helper(nums, start, mid - 1);
    node->right = helper(nums, mid + 1, end);
    
    return node;
}

struct TreeNode* sortedArrayToBST(int* nums, int numsSize){
    return helper(nums, 0, numsSize - 1);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值