Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路: Using slow and fast pointer to find the middle pointer of the link list. Using the slow as the root, fast = slow .next; pre.next = null; slow.next = null;
Then recursion to get the left tree and right tree
易错点: 注意 slow, pre , fast 全指向head 的情况,要将 head 设置成null 来获得一个 null Treenode 一定要断开 slow 前面 和 后面的指针。 顺序问题, 一定要先把 fast = slow.next; 再pre.next = null; 这个关系到全指向head 的情况
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
/**
* Definition for binary tree
* 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;
ListNode slow = head;
ListNode fast = head;
ListNode pre = head;
while(fast.next != null && fast.next.next != null){
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
TreeNode root = new TreeNode(slow.val);
fast = slow.next;
pre.next = null;//-------
slow.next = null;//-----------
if(slow == head){//------
head = null;
}
TreeNode left = sortedListToBST(head);
TreeNode right = sortedListToBST(fast);
root.left = left;
root.right = right;
return root;
}
}