LeetCode - Convert Sorted List to Binary Search Tree

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 };

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3547401.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值