41.有序数组(二叉搜索树)转平衡二叉树

1.题目描述

2.解题思路

递归,依旧看basecase情况

cpp 复制代码
class Solution {
public:
    
    TreeNode* helper(vector<int>& nums, int l, int r){
        if(l > r){
            return nullptr;
        }
   
    int mid = (l + r)/2;
    TreeNode *root  = new TreeNode(nums[mid]);
    root->left = helper(nums, l , mid - 1);
    root->right = helper(nums, mid + 1, r);
    return root;
}
    
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return helper(nums, 0, nums.size() - 1);
        
    }
};
相关推荐
梵刹古音5 小时前
【C语言】 指针与数据结构操作
c语言·数据结构·算法
爱敲代码的TOM7 小时前
数据结构总结
数据结构
皮皮哎哟8 小时前
数据结构:嵌入式常用排序与查找算法精讲
数据结构·算法·排序算法·二分查找·快速排序
堕2749 小时前
java数据结构当中的《排序》(一 )
java·数据结构·排序算法
2302_8138062210 小时前
【嵌入式修炼:数据结构篇】——数据结构总结
数据结构
Wei&Yan10 小时前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
long31611 小时前
Aho-Corasick 模式搜索算法
java·数据结构·spring boot·后端·算法·排序算法
张张努力变强13 小时前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
wWYy.13 小时前
数组快排 链表归并
数据结构·链表
李斯啦果14 小时前
【PTA】L1-019 谁先倒
数据结构·算法