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

108. Convert Sorted Array to Binary Search Tree

时间:2017-02-18 09:34:59      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:etc   order   form   turn   span   new   ted   convert   end   

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

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

2/17/2017, Java

performance不好

 1 public class Solution {
 2     public TreeNode sortedArrayToBST(int[] nums) {
 3         if (nums == null) return null;
 4         return sortedArrayToBST(nums, 0, nums.length - 1);
 5     }
 6     private TreeNode sortedArrayToBST(int[] nums, int lo, int hi) {
 7         if (lo > hi) return null;
 8         int mid = lo + (hi - lo) / 2;
 9         TreeNode ret = new TreeNode(nums[mid]);
10         ret.left = sortedArrayToBST(nums, lo, mid - 1);
11         ret.right = sortedArrayToBST(nums, mid + 1, hi);
12         return ret;
13     }
14 }

 

108. Convert Sorted Array to Binary Search Tree

标签:etc   order   form   turn   span   new   ted   convert   end   

原文地址:http://www.cnblogs.com/panini/p/6412186.html

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