力扣108. 将有序数组转换为二叉搜索树

给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 平衡 二叉搜索树。



提示:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums 按 严格递增 顺序排列

代码:

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* helper(vector<int>& nums, int left, int right){
        if(left > right){
            return nullptr;
        }

        int mid = (left + right) / 2;

        TreeNode* root = new TreeNode(nums[mid]);

        root->left = helper(nums, left, mid-1);
        root->right = helper(nums, mid+1, right);

        return root;
    }

    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return helper(nums, 0, nums.size()-1);
    }
};

解题思路:

(1)注意题目,给出的数组是排序好的。

(2)我们只需每次选择中间的数作为根节点即可。

相关推荐
大今野7 小时前
第 13 章 数据结构:二叉树遍历、栈与队列、图与排序全考点(专转本计算机必考)
数据结构·专转本
饮水桶_T8 小时前
Java调用大语言模型、多轮对话 笔记
笔记·算法·设计模式·电脑·ai编程
AAA修煤气灶刘哥8 小时前
QQ 音乐怎么在 25 毫秒内,决定一句话该交给谁?
人工智能·算法·llm
开开心心就好10 小时前
电脑禁止自动休眠工具,还能按负载定时
算法·智能手机·pdf·电脑·word·音视频·lua
拾码录10 小时前
深入理解链表:动态数据结构的基石
c语言·数据结构·链表
geovindu21 小时前
python:DecisionTree
开发语言·后端·python·算法
geovindu1 天前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
AllData公司负责人1 天前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康1 天前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习