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);
        
    }
};
相关推荐
不会就选b2 分钟前
算法日常・每日刷题--<贪心>3
数据结构·算法·leetcode
ysu_03143 分钟前
03-双链表与循环链表
c语言·数据结构·链表
wabs6661 小时前
关于二叉树【力扣107.二叉树的层序遍历II的思考】
数据结构·c++·算法·leetcode·二叉树·层序遍历
小七在进步2 小时前
数据结构:非比较排序:计数排序
数据结构
一木 之林2 小时前
四、STL 容器与数据结构(进阶)(二)
数据结构·c++·哈希算法
ysu_03142 小时前
02-单链表完全指南
c语言·数据结构·算法·leetcode
Lyyaoo.3 小时前
【链表】【中等】两数相加/倒N删除/两个交换/排序链表/LRU缓存
数据结构·链表·缓存
bro_Java6663 小时前
链表进阶:链表笔试真题
数据结构·链表
LB21123 小时前
力扣102 198 70 55
数据结构·算法·leetcode
刘天远4 小时前
企业 Agent 需求怎么写:数据结构、流程图与 Python 校验
数据结构·人工智能·python·流程图