Question
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Explanation
和108题类似,唯一不同的是linkedinlist。用两个pointer找到中心点就好。
Code
123456789101112131415161718192021public class Solution {public TreeNode sortedListToBST(ListNode head) { if(head==null) return null; return toBST(head,null);}public TreeNode toBST(ListNode head, ListNode tail){ ListNode slow = head; ListNode fast = head; if(head==tail) return null; while(fast!=tail&&fast.next!=tail){ fast = fast.next.next; slow = slow.next; } TreeNode thead = new TreeNode(slow.val); thead.left = toBST(head,slow); thead.right = toBST(slow.next,tail); return thead;}}