Convert sorted list to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Algorithm ideas:
It is similar to [leetcode] convert sorted array to binary search tree, but there is no essential difference between array and list.
Three steps:
Find the midpoint (speed pointer)
Broken linked list (the precursor to slow pointer needs to be found)
Sub-governance.
The Code is as follows:
1 public class Solution { 2 public TreeNode sortedListToBST(ListNode head) { 3 if(head == null) return null; 4 if(head.next == null) return new TreeNode(head.val); 5 ListNode hhead = new ListNode(0); 6 hhead.next = head; 7 ListNode fast = hhead, slow= hhead; 8 while(fast != null && fast.next != null){ 9 fast = fast.next.next;10 slow = slow.next;11 }12 TreeNode root = new TreeNode(slow.val);13 ListNode right = slow.next;14 ListNode pre = hhead;15 while(pre != null && pre.next != slow){16 pre = pre.next;17 }18 pre.next = null;19 ListNode left = hhead.next;20 root.left = sortedListToBST(left);21 root.right = sortedListToBST(right);22 return root;23 }24 }