【LeetCode算法】第108题:将有序数组转换为二叉搜索树

目录

一、题目描述

二、初次解答

三、官方解法

四、总结


一、题目描述

二、初次解答

1. 思路:由于数组nums是递增的,采用二分查找法来构造平衡二叉搜索树。首先,选择nums的中间结点作为根节点,然后将左部分的中间值作为左子树,将右部分的中间值作为右子树,以此类推。

2. 代码:

void constructTree(int start, int end, int* nums, struct TreeNode** root){
    if(start > end){
        *root=NULL;
        return;
    }
    int mid=(start+end)/2;
    *root=(struct TreeNode*)malloc(sizeof(struct TreeNode));
    (*root)->val=nums[mid];
    constructTree(start, mid-1, nums, &((*root)->left));
    constructTree(mid+1, end, nums, &((*root)->right));
}

struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
    struct TreeNode* target=NULL;
    constructTree(0, numsSize-1, nums, &target);
    return target;
}

3. 优点:仅遍历一遍数组,时间复杂度为O(n)。

4. 缺点:采用了递归,空间复杂度为O(log n)。

三、官方解法

官方解法均类似,都是采用二分方式来构建平衡二叉搜索树,时间和空间复杂度都一样。

四、总结

将升序/降序的数组构建为平衡二叉搜索树,可以使用二分查找的方法来递归构建。

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-07 00:40:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-07 00:40:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-07 00:40:01       82 阅读
  4. Python语言-面向对象

    2024-06-07 00:40:01       91 阅读

热门阅读

  1. npm:Node.js包管理器的使用指南

    2024-06-07 00:40:01       24 阅读
  2. 【机器学习】之 kmean算法原理及实现

    2024-06-07 00:40:01       31 阅读
  3. DVWA-CSRF

    DVWA-CSRF

    2024-06-07 00:40:01      25 阅读
  4. 算法学习笔记——对数器

    2024-06-07 00:40:01       30 阅读
  5. 递推7-2 sdut-C语言实验-养兔子分数

    2024-06-07 00:40:01       23 阅读
  6. MacBook M系列芯片安装php8.2

    2024-06-07 00:40:01       31 阅读
  7. 【html知识】html中常用的表单元素+css格式美化

    2024-06-07 00:40:01       31 阅读