力扣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;
    }
}
相关推荐
QC班长1 小时前
Maven公司私库配置踩坑点
java·服务器·maven·intellij-idea
Makoto_Kimur1 小时前
java开发面试-AI Coding速成
java·开发语言
wuqingshun3141592 小时前
说说mybatis的缓存机制
java·缓存·mybatis
知识浅谈2 小时前
DeepSeek V4 和 GPT-5.5 在同一天发布了??我也很懵,但对比完我悟了
算法
DeepModel2 小时前
通俗易懂讲透 Q-Learning:从零学会强化学习核心算法
人工智能·学习·算法·机器学习
田梓燊2 小时前
力扣:19.删除链表的倒数第 N 个结点
算法·leetcode·链表
空中海2 小时前
Kubernetes 生产实践、可观测性与扩展入门
java·贪心算法·kubernetes
Devin~Y3 小时前
大厂Java面试实录:Spring Boot/Cloud、Kafka、Redis、K8s 与 Spring AI(RAG/Agent)三轮连环问
java·spring boot·redis·mysql·spring cloud·kafka·kubernetes
bLEd RING3 小时前
SpringBoot3.3.0集成Knife4j4.5.0实战
java
小松加哲3 小时前
Spring MVC 核心原理全解析
java·spring·mvc