随笔- 509  文章- 0  评论- 151  阅读- 22万 

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   zhuli19901106  阅读(192)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示