Convert Sorted List to Binary Search Tree

2014.2.13 00:46

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

Solution:

  You may already have solved the problem Convert Sorted Array to Binary Search Tree, which can be done in O(n) time.

  Since linked list is sequential data structure, accessing a node requires O(n) time. The solution is similar for this problem, but time complexity is O(n * log(n)), instead of O(n). Space complexity remains the same O(n).

  T(n) = 2 * T(n / 2)  + O(n) => T(n) = O(n * log(n))

  Another more efficient solution is to convert the linked list to array using an extra vector, and Convert Sorted Array to Binary Search Tree. At least both steps run in O(n) time, it's more efficient after all. Space complexity remains in O(n) scale, but the constant scalar becomes larger.

Accepted code:

 1 // 1CE, 1AC, excellent.
 2 /**
 3  * Definition for singly-linked list.
 4  * struct ListNode {
 5  *     int val;
 6  *     ListNode *next;
 7  *     ListNode(int x) : val(x), next(NULL) {}
 8  * };
 9  */
10 /**
11  * Definition for binary tree
12  * struct TreeNode {
13  *     int val;
14  *     TreeNode *left;
15  *     TreeNode *right;
16  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
17  * };
18  */
19 class Solution {
20 public:
21     TreeNode *sortedListToBST(ListNode *head) {
22         if (head == nullptr) {
23             return nullptr;
24         }
25         int n = 0;
26         ListNode *ptr = head;
27         while (ptr !=  nullptr) {
28             ptr = ptr->next;
29             ++n;
30         }
31         
32         if (n == 1) {
33             return new TreeNode(head->val);
34         }
35         
36         int nl, nr;
37         int i;
38         ListNode *head1, *root, *head2;
39         
40         nr = (n - 1) / 2;
41         nl = n - 1 - nr;
42         // nl must be positive
43         // nr could be 0
44         ptr = head;
45         for (i = 0; i < nl - 1; ++i) {
46             ptr = ptr->next;
47         }
48         head1 = head;
49         root = ptr->next;
50         ptr->next = nullptr;
51         head2 = root->next;
52         root->next = nullptr;
53         
54         TreeNode *tree_root = nullptr;
55         
56         tree_root = new TreeNode(root->val);
57         tree_root->left = sortedListToBST(head1);
58         tree_root->right = sortedListToBST(head2);
59         
60         return tree_root;
61     }
62 };

 

 posted on 2014-02-13 01:00  zhuli19901106  阅读(191)  评论(0编辑  收藏  举报