Middle-题目15:108. Convert Sorted Array to Binary Search Tree

题目原文:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题目大意:
把一个升序排列的数组构建成BST(二叉排序树)。
题目分析:
数组的中点是二叉排序树的根节点,然后递归把左半边和右半边递归构建成左子树和右子树。
源码:(language:java)

public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums.length==0)
            return null;
        TreeNode bst=createBST(nums,0,nums.length-1);
        return bst;
    }
    public TreeNode createBST(int[] nums,int start,int end) {
        int mid = (start + end) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        if(start < mid ) 
            root.left = createBST(nums,start,mid-1);
        if(mid  < end) 
            root.right = createBST(nums,mid+1,end); 
        return root;
    }
}

成绩:
1ms,beats 7.24%,众数1ms,92.62%

阅读更多
版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs https://blog.csdn.net/cmershen/article/details/51546260
个人分类: Leetcode
上一篇Middle-题目14:141. Linked List Cycle
下一篇Middle-题目16:230. Kth Smallest Element in a BST
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭