LeetCode--108. Convert Sorted Array to Binary Search Tree详解

题目链接:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

题目要求将排序数组转为平衡二叉搜索树,先说一下二叉搜索树(Binary search tree)的定义和特性(wikipedia):

对应本题核心特点是:左子节点值小于等于父节点的值,右子节点大于父节点里的值。再来看“平衡”,题目中也给出“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”,而且LeetCode--110. Balanced Binary Tree就是要求判断是否为平衡二叉树。

讲了这么多前置知识,来谈谈思路,举个例子看看:

                     

对应的平衡二叉搜索树是:

                                             

在OJ上验证也是[-3,-8,6,-10,-6,0,7,null,-9,null,-4,null,5,null,8]就证明了我的一个思路:

对于排序(子)数组A,起始索引i和终点索引j,mid=i+(j-i)/2就是当前树的根节点root,然后A[i,mid-1]构成root的左子树上,A[mid+1,j]构成root的右子树,这是一个层层递归的过程,每个节点既是单个节点,也代表以自身为根节点的一个子树。说到这儿,是不是感觉有点像归并排序的算法思路。详情看图示:

这样递归主体代码就写出来了:

class Solution {
    
        public TreeNode sortedArrayToBST(int[] nums)
        {
            if(nums.length==0 || nums==null)
                return null;
            int i=0,j=nums.length-1;
            
            return recursive(nums,i,j);
        }
    
    public TreeNode recursive(int[] nums,int i,int j)
    {
        int mid=(j-i)/2+i;
        TreeNode root=new TreeNode(nums[mid]);
        root.left=recursive(nums,i,mid-1);
        root.right=recursive(nums,mid+1,j);
        return root;
    }
}

其实最关键的就是写出递归的终止条件:

这里就是当i和j指向同一数组元素或者无法对应数组元素时需要return

if(i>j)
    return null;
if(i==j)
    return new TreeNode(nums[i]);

完整代码如下:

class Solution {
    
        public TreeNode sortedArrayToBST(int[] nums)
        {
            if(nums.length==0 || nums==null)
                return null;
            int i=0,j=nums.length-1;
            
            return recursive(nums,i,j);
        }
    
    public TreeNode recursive(int[] nums,int i,int j)
    {
        if(i>j)
            return null;
        if(i==j)
            return new TreeNode(nums[i]);
        int mid=(j-i)/2+i;
        TreeNode root=new TreeNode(nums[mid]);
        root.left=recursive(nums,i,mid-1);
        root.right=recursive(nums,mid+1,j);
        return root;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值