力扣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;
    }
}
相关推荐
jinanwuhuaguo1 天前
OpenClaw办公人员核心技能深度培训体系:从认知重塑到数字组织构建的全链路实战指南
java·大数据·开发语言·人工智能·openclaw
旖-旎1 天前
分治(交易逆序对的总数)(6)
c++·算法·leetcode·排序算法·归并排序
北顾笙9801 天前
day14-数据结构力扣
数据结构·算法·leetcode
zihao_tom1 天前
Spring Boot 整合 Druid 并开启监控
java·spring boot·后端
不会写DN1 天前
Protocol Buffers(.proto)实战入门:Go 生态最常用的接口定义语言
java·前端·golang
lifallen1 天前
Flink Agents:从 DataStream 到 Agent 算子的接入与装配
java·大数据·人工智能·python·语言模型·flink
oYD3FlT321 天前
MyBatis-缓存与注解式开发
java·缓存·mybatis
Arya_aa1 天前
Web基础+JavaEE+容器
java·java-ee
Ln5x9qZC21 天前
尾递归与Continuation
算法
一路向北he1 天前
esp32库依赖
c语言·c++·算法