Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
一刷
题解:利用快慢指针找到median, 快指针每次移动两步, 慢指针每次移动一步。最后慢指针所在位置为median. 并且,这题很自然地用recursion做更方便。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
return toBST(head, null);
}
TreeNode toBST(ListNode head, ListNode tail){
ListNode slow = head;
ListNode fast = head;
if(head == tail) return null;
//the place of slow is the median
while(fast!=tail && fast.next!=tail){
fast = fast.next.next;
slow = slow.next;
}
TreeNode thread = new TreeNode(slow.val);
thread.left = toBST(head, slow);
thread.right = toBST(slow.next, tail);
return thread;
}
}
二刷:
第二遍做还是忘了可以用快慢指针得到medium的位置。 recursion求解
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
return sortedListToBST(head, null);
}
private TreeNode sortedListToBST(ListNode head, ListNode tail){
if(head == null || head == tail) return null;
ListNode fast = head, slow = head;
while(fast!=tail && fast.next!=tail){
fast = fast.next.next;
slow = slow.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = sortedListToBST(head, slow);
root.right = slow==null? null:sortedListToBST(slow.next, tail);
return root;
}
}
三刷
注意快慢指针的使用
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
return toBST(head, null);
}
public TreeNode toBST(ListNode from, ListNode to){
//not include null
if(from == to || from == null) return null;
ListNode med = findMedium(from, to);
TreeNode root = new TreeNode(med.val);
root.left = toBST(from, med);
if(med == null) root.right = null;
else root.right = toBST(med.next, to);
return root;
}
private ListNode findMedium(ListNode head, ListNode tail){
ListNode slow = head;
ListNode fast = head;
while(fast!=tail && fast.next!=tail){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}