码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Convert Sorted List to Binary Search Tree

时间:2015-02-26 19:58:04      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

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

[LeetCode] Convert Sorted List to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/vincently/p/4301973.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!