Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Java语言: SortedListToBST
01 public TreeNode sortedListToBST(ListNode head) {
02 //two base cases
03 if(head==null)
04 return null;
05 if(head.next==null)
06 return new TreeNode(head.val);
07
08 //partition the list from the middle, use two pointers
09 //the slow pointer will be the prev of the middle node
10 ListNode fast=head.next.next;
11 ListNode slow=head;
12 while(fast!=null && fast.next!=null)
13 {
14 fast=fast.next.next;
15 slow=slow.next;
16 }
17 //find the middle node
18 ListNode parent=slow.next;
19 slow.next=null;
20
21 //partition the list into left and right
22 ListNode left=head;
23 ListNode right=parent.next;
24 parent.next=null;
25
26 //make the middle node as the root, then apply the function
27 //to the left part and the right part recursively
28 TreeNode root=new TreeNode(parent.val);
29 root.left=sortedListToBST(left);
30 root.right=sortedListToBST(right);
31 return root;
32 }
33 }
02 //two base cases
03 if(head==null)
04 return null;
05 if(head.next==null)
06 return new TreeNode(head.val);
07
08 //partition the list from the middle, use two pointers
09 //the slow pointer will be the prev of the middle node
10 ListNode fast=head.next.next;
11 ListNode slow=head;
12 while(fast!=null && fast.next!=null)
13 {
14 fast=fast.next.next;
15 slow=slow.next;
16 }
17 //find the middle node
18 ListNode parent=slow.next;
19 slow.next=null;
20
21 //partition the list into left and right
22 ListNode left=head;
23 ListNode right=parent.next;
24 parent.next=null;
25
26 //make the middle node as the root, then apply the function
27 //to the left part and the right part recursively
28 TreeNode root=new TreeNode(parent.val);
29 root.left=sortedListToBST(left);
30 root.right=sortedListToBST(right);
31 return root;
32 }
33 }
没有评论:
发表评论