[LeetCode] 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.

解法:自底向上

     时间复杂度O(n), 空间复杂度O(logN)

 1 class Solution {
 2 public:
 3     TreeNode *sortedListToBST(ListNode *head) {
 4         if (head == NULL) return NULL;
 5         
 6         int len = 0;
 7         ListNode *p = head;
 8         while (p) {
 9             ++len;
10             p = p->next;
11         }
12         
13         return sortedListToBST(head, 0, len - 1);
14     }
15     
16     TreeNode* sortedListToBST(ListNode *&head, int start, int end) {
17         if (start > end) return NULL;
18         
19         int mid = start + (end - start) / 2;
20         TreeNode *left_child = sortedListToBST(head, start, mid - 1);
21         TreeNode *root = new TreeNode(head->val);
22         root->left = left_child;
23         head = head->next;
24         root->right = sortedListToBST(head, mid + 1, end);
25         
26         return root;
27     }
28 };

 参考资料:

  1.http://leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html

posted @ 2015-02-26 19:16  vincently  阅读(201)  评论(0编辑  收藏  举报