Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* 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) {
return helper(head, null);
}
public TreeNode helper(ListNode head, ListNode tail) {
if (head == null || head == tail){
return null;
}
ListNode slow = head;
ListNode fast = head;
while (fast.next != tail && fast.next.next != tail){
fast = fast.next.next;
slow = slow.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = helper(head, slow);
root.right = helper(slow.next, tail);
return root;
}
}