Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public class Solution {
- public TreeNode sortedListToBST(ListNode head) {
- ListNode t = head;
- int count = 0;
- while(t!=null){
- count++;
- t = t.next;
- }
- int[] nums = new int[count];
- t = head;
- int i=0;
- while(t!=null){
- nums[i++] = t.val;
- t = t.next;
- }
- return helper(nums, 0, nums.length-1);
- }
-
- public TreeNode helper(int[] nums,int start,int end){
- if(start>end) return null;
- if(start==end) return new TreeNode(nums[start]);
- int mid = start+(end-start)/2;
- TreeNode t = new TreeNode(nums[mid]);
- t.left = helper(nums, start, mid-1);
- t.right = helper(nums, mid+1, end);
- return t;
- }
- }
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46484695