Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
第一反應(yīng)就是用快慢指針找鏈表中點(diǎn)!!!然而這個(gè)方法還是使用的不熟練,不知道應(yīng)該怎么設(shè)置終止條件!!!
還是要反復(fù)練習(xí)!!!
一般情況,slow和fast指針都指向head節(jié)點(diǎn),while循環(huán)條件為fast != null && fast.next != null!!!
corner case有:
1)head==null,直接判斷,一般是直接返回null即可。
2)head.next == null,即鏈表中僅一個(gè)元素。此時(shí)由于fast指針一開始指向head,若僅一個(gè)head元素,則fast無法連續(xù)往后跳2格!!!因此也許特別考慮。
本題還有一個(gè)trick的地方在于,循環(huán)結(jié)束slow指針指向中點(diǎn)后,還需要將slow前一個(gè)指針prev設(shè)置為prev.next = null,即切斷鏈表前半段與slow的聯(lián)系!!!
如何實(shí)現(xiàn)?!
開始就采用一個(gè)prev指針,設(shè)為null,每次slow向后移動(dòng),prev也向后移動(dòng)!!!
有一點(diǎn)要注意,若prev一直為null,說明鏈表中只有一個(gè)head元素,并沒有進(jìn)入while循環(huán)移動(dòng)快慢指針!!!
代碼:
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
ListNode prev = null;
ListNode slow = head, fast = head;
// find the median node in the linked list, after executing this loop
// fast will pointing to the last node, while slow is the median node.
while (fast != null && fast.next != null) {
fast = fast.next.next;
prev = slow;
slow = slow.next;
}
if (prev != null) prev.next = null;
else head = null;
TreeNode node = new TreeNode(slow.val);
node.left = sortedListToBST(head);
node.right = sortedListToBST(slow.next);
return node;
}
}
參考:
https://discuss.leetcode.com/topic/8141/share-my-o-1-space-and-o-n-time-java-code/4