LeetCode 109. Convert Sorted List to Binary Search Tree

原题链接在这里:https://leetcode.com/problems/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.

题解:

找到List中点当BST的root. 中点之前当左子树,中点之后当右子树。

递归调用,终止条件有两个: 第一,当ListNode 为 null 时返回null.

第二,当只有一个ListNode时返回由当前点生成的TreeNode.

Note:此处findMidLeft找到的是中点的前一个点,然后拆成三段,中点前一段,中点单独一个,中点后一段.

Time Complexity: O(n*logn), 因为T(n) = 2*T(n/2) + n, findMidLeft 用了n时间, n是List长度。

Space: O(logn),  一共用了O(logn) 层stack.

AC Java:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 /**
10  * Definition for a binary tree node.
11  * public class TreeNode {
12  *     int val;
13  *     TreeNode left;
14  *     TreeNode right;
15  *     TreeNode(int x) { val = x; }
16  * }
17  */
18 public class Solution {
19     public TreeNode sortedListToBST(ListNode head) {
20         if(head == null){
21             return null;
22         }
23         
24         if(head.next == null){
25             return new TreeNode(head.val);
26         }
27         ListNode midLeft = findMidLeft(head);
28         ListNode mid = midLeft.next;
29         ListNode midRight = mid.next;
30         
31         //Break
32         midLeft.next = null;
33         mid.next = null;
34         
35         //Create root;
36         TreeNode root = new TreeNode(mid.val);
37         root.left = sortedListToBST(head);
38         root.right = sortedListToBST(midRight);
39         return root;
40     }
41     
42     private ListNode findMidLeft(ListNode head){
43         if(head == null || head.next == null){
44             return head;
45         }
46         ListNode walker = head;
47         ListNode runner = head;
48         while(runner.next != null && runner.next.next != null && runner.next.next.next != null){
49             walker = walker.next;
50             runner = runner.next.next;
51         }
52         return walker;
53     }
54     
55 }

类似Convert Sorted Array to Binary Search Tree.

posted @ 2015-09-03 03:36  Dylan_Java_NYC  阅读(370)  评论(0编辑  收藏  举报