Convert Sorted Array to Binary Search Tree

有序数组转平衡二叉树
本文介绍如何将一个升序排列的数组转换为高度平衡的二叉搜索树。通过递归方式选取数组中间元素作为根节点,并递归构建左右子树,确保树的高度平衡。

题目描述

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.

解题思路

将一个排好序的数组转化为二叉搜索树—-采用递归方式,每次取中间的数字作为树的根节点,数组的左半边作为左子树,右半边作为右子树
由于平均递归创建每一层的子树,所以两个子树的高度差不会超过1。

代码:

public TreeNode sortedArrayToBST(int[] num) {
    if(num==null || num.length==0)
        return null;
    return helper(num,0,num.length-1);
}
private TreeNode helper(int[] num, int l, int r)
{
    if(l>r)
        return null;
    int m = (l+r)/2;
    TreeNode root = new TreeNode(num[m]);
    root.left = helper(num,l,m-1);
    root.right = helper(num,m+1,r);
    return root;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值