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

解题思路:

二叉搜索树一般使用中序遍历

java 复制代码
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return helper(nums,0,nums.length-1);
    }
    public TreeNode helper(int[] nums,int left,int right){
        if(left>right) return null;

        //确定根节点
        //总是选择中间位置左边的数字作为根节点
        //也可以用 int mid = (left + right + 1) / 2; 总是选择中间位置右边的数字作为根节点
        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;
    }
}
相关推荐
sun03224 分钟前
【JDK 动态代理】 和 【CGLIB 代理】对比
java·数据库·sql
文丑颜不良啊5 分钟前
LeetCode1261~1280题目解析
java·leetcode
郭小李6 分钟前
spring 中的 @EnableWebMvc注解和WebMvcConfigurer接口
java·后端·spring
not coder10 分钟前
一文讲通--从树到红黑树
数据结构·算法
octopus_c12 分钟前
C++ 入门
开发语言·c++·算法
ZhengEnCi26 分钟前
2026年10月30日AI早报:Gemini 4 Carbon登顶、DeepSeek融资1055亿、智元机器人上岗实测
人工智能·算法
强哥聊算力38 分钟前
《算力江湖·Intel帝国往事》第三集:安迪·格鲁夫的铁血时代:Intel为什么能把对手逼到墙角?
运维·人工智能·科技·算法·ai·gpu算力
香蕉大香蕉(06敬畏市场)1 小时前
高频八股 · JVM(8)
java·jvm·面试·八股·大厂实习
Shaoshing1 小时前
LeetCode100 11. 盛最多水的容器
算法·leetcode
养军博客1 小时前
spirngSecurity 鉴权教程02
java·springsecurity