题目:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
思路:
从中间开始遍历,快慢指针,快next两下,慢next一下,到了最后慢就是在中间了。
然后左右分别是左子树和右子树
Code:
public TreeNode sortedListToBST(ListNode head) {
return aBST(head,null);
}
public TreeNode aBST(ListNode head,ListNode tail){
if (head==tail) return null;
ListNode fast = head;
ListNode slow = head;
while(fast!=tail){
fast = fast.next;
if(fast!=tail){
fast = fast.next;
slow = slow.next;
}
}
TreeNode root = new TreeNode(slow.val);
root.left = aBST(head,slow);
root.right = aBST(slow.next,tail);
return root;
}