首页 > 代码库 > [leetcode]Convert Sorted List to Binary Search Tree

[leetcode]Convert Sorted List to Binary Search Tree

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.

算法思路:

与[leetcode]Convert Sorted Array to Binary Search Tree很相似,不过一个是array,一个是list,无本质区别。

三步走:

找中点(快慢指针)

断链表(需要找慢指针的前驱)

分治。

 

代码如下:

 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 }