Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Convert Sorted List to Binary Search Tree
 1  //              We shuould use a static variable int the recursive function!!!!
 2 public class Solution {
 3     static ListNode h;
 4     public TreeNode sortedListToBST(ListNode head) {
 5         if(head==null) return null;
 6         h = head;
 7         ListNode p =head;
 8         int len = 0;
 9         while(p!=null){
10             len++;
11             p=p.next;
12         }
13         
14         return get(0,len-1);
15     }
16     public TreeNode get(int start,int end){
17         if(start>end) return null;
18        int mid=start+(end-start)/2;
19        TreeNode left = get(start, mid-1);
20        TreeNode parent = new TreeNode(h.val);
21        parent.left = left;
22        h = h.next;
23        parent.right= get(mid+1,end);
24        return parent;
25     }
26 }
View Code

Convert Sorted List to Binary Search Tree

上一篇:Combination Sum II


下一篇:Combinations