码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Convert Sorted Array to Binary Search Tree

时间:2016-01-10 12:55:55      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

思路:

总是取中间点为root

package bst;

public class ConvertSortedArrayToBinarySearchTree {

    public TreeNode sortedArrayToBST(int[] nums) {
        return constructBST(nums, 0, nums.length - 1);
    }

    private TreeNode constructBST(int[] nums, int start, int end) {
        if (start > end) return null;
        int mid = (end - start) / 2 + start;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = constructBST(nums, start, mid - 1);
        root.right = constructBST(nums, mid + 1, end);
        return root;
    }
    
}

 

LeetCode - Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/shuaiwhu/p/5118120.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!