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);
        
    }
};
相关推荐
琢磨先生David3 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_454245033 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝3 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA3 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc3 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg13 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA3 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法
czxyvX3 天前
020-C++之unordered容器
数据结构·c++
岛雨QA3 天前
多路查找树「Java数据结构与算法学习笔记11」
数据结构·算法
AKA__Zas3 天前
初识基本排序
java·数据结构·学习方法·排序