Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

 

Show Tags

SOLUTION 1:

这个方法比较暴力,每次遍历当前list,找到中间的节点,建立 root,分别使用递归建立左树以及右树,并将左右树挂在root之下。但这个算法会复杂度很高。
建立root次数为N,每次遍历最多N次,最坏为N平方(实际不会这么多)
 1 public TreeNode sortedListToBST1(ListNode head) {
 2         ListNode fast = head;
 3         ListNode slow = head;
 4         
 5         ListNode pre = head;
 6         
 7         if (head == null) {
 8             return null;
 9         }
10         
11         TreeNode root = null;
12         if (head.next == null) {
13             root = new TreeNode(head.val);
14             root.left = null;
15             root.right = null;
16             return root;
17         }
18         
19         // get the middle node.
20         while (fast != null && fast.next != null) {
21             fast = fast.next.next;
22             
23             // record the node before the SLOW.
24             pre = slow;
25             slow = slow.next;
26         }
27         
28         // cut the list to two parts.
29         pre.next = null;
30         TreeNode left = sortedListToBST1(head);
31         TreeNode right = sortedListToBST1(slow.next);
32         
33         root = new TreeNode(slow.val);
34         root.left = left;
35         root.right = right;
36         
37         return root;
38     }
View Code

 

相关文章: