leetcode108_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.

Example:

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

二叉搜索树BST(Binary Search Tree)其定义:

1 首先它也是一个二叉树,故满足递归定义;

2 其次每个节点只存在一个值;

3 需满足左子树值<=根值<=右子树,故按照中序遍历会得到一个非递减序列。

这道题直接参考了网上的思路,大家用的都是递归的方法

解题思路:从递归出发,但是要结合二叉查找树的定义,每次将数组二分中间值作为根节点,依次递归二分并将中间值赋值给根节点,最后返回根结点,递归返回的临界条件是:左索引大于右索引


//主体部分是从数组的两端向中间扫描,每次都新建mid值为根节点,并指定左区间的下一轮返回mid值为其左节点,指定右区间的下一轮返回mid值为其右节点。
class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
       return buildTree(num,0,num.length-1);//迭代
    }
    public TreeNode buildTree(int[] num, int low, int high){
        if(low>high)//递归终止条件为左索引大于右索引,不包括等于以免遗漏元素,只有最后一层的叶子节点中可以存在null空元素
            return null;

        int mid = (low+high)/2;//二分法的中间节点是两端点的平均值,如果为1.5则int之后取1
        TreeNode node = new TreeNode(num[mid]);//新建mid值为根节点
        node.left = buildTree(num,low,mid-1);//根节点的左节点,是来自下一轮针对左区间递归的mid值
        node.right = buildTree(num,mid+1,high);//根节点的右节点,是来自下一轮针对右区间递归的mid

        return node;//子函数返回值为node节点,每一次调用的时候都会返回,因此会自上而下,从中间向两侧的建立起二叉树
    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值