Convert Sorted Array to Binary Search Tree

给定一个升序排列的数组,将其转换为高度平衡的二叉搜索树。高度平衡的定义是,每个节点的两棵子树深度之差不超过1。通过二分法,找到数组中间元素作为根节点,再递归地将左右子数组转化为平衡的二叉搜索树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Convert Sorted Array to Binary Search Tree

Description

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example 1:
Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

Tags: Tree

解读题意

给定一个有序的数组,将其组成一个查找二叉树,即BST。BST需要满足:左结点 < 中结点 < 右结点特性。

思路1

如果将查找二叉树进行中序遍历,得到的便是一个有序数组。那么反过来,根结点便是有序数组的中点。接下来用二分法的思想来解决创建出查找二叉树。
1. 找到有序数组的中点int mid = (nums.length - 1)/2,将数组分为左右两个数组
2. 以当前中点的值nums[mid]创建根结点
3. 再分别以左右两个有序数组为原型,递归执行步骤1,2

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null || nums.length == 0)
            return null;

        return sortedArrayToBSTHelper(nums, 0, nums.length - 1);
    }


    private TreeNode sortedArrayToBSTHelper(int[] nums, int left, int right) {
        if (left > right)
            return null;

        int mid = (left + right) / 2;

        TreeNode root = new TreeNode(nums[mid]);
        root.left = sortedArrayToBSTHelper(nums, left, mid - 1);
        root.right = sortedArrayToBSTHelper(nums, mid + 1, right);

        return root;
    }

}

time complexity:O(n)

leetCode汇总:https://blog.youkuaiyun.com/qingtian_1993/article/details/80588941

项目源码,欢迎star:https://github.com/mcrwayfun/java-leet-code

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值