力扣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;
    }
}
相关推荐
文丑颜不良啊1 小时前
LeetCode3281~3300题目解析
java·leetcode
nice_lcj5202 小时前
【从零理解计算机网络 · 02】分层模型:别背 OSI 七层,看数据怎么被“打包“和“拆包“
java·后端·tcp/ip·计算机网络·面试·osi·分层模型
地平线开发者2 小时前
让 AI Agent 和 征程6 台架高效、稳定、安全地协作
算法·安全·自动驾驶
SimonKing3 小时前
给Deepseek Harness装上插件市场,从此插件无忧
java·后端·程序员
艾莉丝努力练剑3 小时前
【AI大模型接入SDK】C++的SessionManager 线程安全
java·开发语言·前端·c++·人工智能·学习·安全
kyle~3 小时前
SHA-256 哈希去重
算法·哈希算法
aiotto资源分享3 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
RuoyiOffice4 小时前
SpringBoot3+Vue3 采购到付款:ERP、WMS与财务如何按同一来源协同
java·spring boot·架构·vue
文丑颜不良啊4 小时前
LeetCode3261~3280题目解析
java·leetcode
代码不停4 小时前
Spring 原理
java·spring