Cyberpunker
Junior Member
Java:
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
if (head.next == null) return new TreeNode(head.val);
ListNode fast=head, slow=head;
while (true) {
fast = fast.next.next;
if (fast == null || fast.next == null) break;
slow = slow.next;
}
ListNode root = slow.next;
slow.next = null;
TreeNode node = new TreeNode(root.val);
node.left = sortedListToBST(head);
node.right = sortedListToBST(root.next);
return node;
}
}