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

原创 2016年05月31日 15:39:29

题目原文:
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

相关文章推荐

【LeetCode-面试算法经典-Java实现】【108-Convert Sorted Array to Binary Search Tree(排序数组转变为平衡二叉树)】

【108-Convert Sorted Array to Binary Search Tree(排序数组转变为平衡二叉树)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  ...

LeetCode 108, 109. Convert Sorted Array/List to Binary Search Tree

1. 题目描述 Given an array where elements are sorted in ascending order, convert it to a height bal...

LeetCode(108)Convert Sorted Array to Binary Search Tree

题目如下: 分析如下: 递归进行。每次找到排序数组的中点,中点左边的子排序数组构成左子树,中点右边的子排序数组构成右子树。就这样递归进行。由于每次都几乎做到了二分,所以每次的左子树和右子树的节点数量是...

LeetCode108 Convert Sorted Array to Binary Search Tree

详细见:leetcode.com/problems/convert-sorted-array-to-binary-search-tree Java Solution: github p...

leetcode108~Convert Sorted Array to Binary Search Tree

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

Leetcode 108 Convert Sorted Array to Binary Search Tree 有序数组构造平衡二叉查找树

给出一个有序数组(递增),使用该数组构造一个平衡二叉查找树。

[leetcode]108. Convert Sorted Array to Binary Search Tree@Java解题报告

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ Given a...

【LeetCode】108. Convert Sorted Array to Binary Search Tree 解法及注释,分治法,递归

108. Convert Sorted Array to Binary Search Tree Total Accepted: 73365 Total Submissions: 197776 Di...

LeetCode- 108/109. Convert Sorted Array/List to Binary Search Tree (JAVA)

LeetCode- 108/109. Convert Sorted Array/List to Binary Search Tree (JAVA),109. Convert Sorted List ...

LeetCode 108. Convert Sorted Array to Binary Search Tree

题目: Given an array where elements are sorted in ascending order, convert it to a height balanced BS...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)