LeetCode - Convert Sorted Array to Binary Search Tree

题注

LeetCode AC Rate中间的很多题也做完了,不过代码在学校的电脑里面。为了保证在学校能干正事(这一碰代码根本停不下来…),以后做题尽量在家里做,作为消遣吧… 新的学期快开始了,昨天和导师交流以后今年的工作任务什么的都定了下来,学期结束前应该没有那么多时间天天刷LeetCode了,尽力而为吧… 今天先把21,22,23三道题的答案更新了,以后有时间,或者没时间做新题的时候就把前面缺的题目们都补上。

题目

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

分析

有关BST的概念在前面的博客《Leetcode - 6 - Unique Binary Search Trees》中已经介绍过了,在此就不重复说明了。对于同一个排序好的数组,其BST的形式其实有非常多种,我们只要找一个最容易生成的即可。那么,最容易生成的BST是什么样子的呢?BST根本的目的是进行二分查找,我们可以考虑生成一个严格满足二分查找特性的BST。也就是说,给定一个数组,其中间元素为Root Node,所有左边的元素递归生成子BST,所有右边的元素也递归生成子BST,且所有偶数个元素个数的数组,要求多出的元素归给右子树,我们来举个例子:

给定数组:{1, 2, 3, 4, 5, 6, 7, 8}

其BST生成的图像表示如下:

{1   2   3   4   5   6   7   8}

                 4

               /    \

 {1   2   3}    {5   6   7   8}

                 4

              /      \

            2       6

          /    \    /   \

      {1}  {3} {5} {7   8}

这种生成形式用递归的方法最容易解决,直接上代码吧!

代码

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        if (num == null || num.length == 0){
            return null;
        } else {
            int middle = (num.length - 1) / 2;
            TreeNode treeNode = new TreeNode(num[middle]);
            if (num.length == 1){
                return treeNode;
            } else {
                int[] leftSortedArray = new int[middle];
                int[] rightSortedArray = new int[num.length - leftSortedArray.length - 1];
                System.arraycopy(num, 0, leftSortedArray, 0, leftSortedArray.length);
                System.arraycopy(num, leftSortedArray.length + 1, rightSortedArray, 0, rightSortedArray.length);
                treeNode.left = sortedArrayToBST(leftSortedArray);
                treeNode.right = sortedArrayToBST(rightSortedArray);
                return treeNode;
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值