Skip to content

Commit 323fc33

Browse files
authored
Create convert-sorted-list-to-binary-search-tree.cpp
1 parent c107db2 commit 323fc33

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Time: O(n)
2+
// Space: O(logn)
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* struct ListNode {
7+
* int val;
8+
* ListNode *next;
9+
* ListNode(int x) : val(x), next(NULL) {}
10+
* };
11+
*/
12+
/**
13+
* Definition for a binary tree node.
14+
* struct TreeNode {
15+
* int val;
16+
* TreeNode *left;
17+
* TreeNode *right;
18+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
19+
* };
20+
*/
21+
class Solution {
22+
public:
23+
TreeNode* sortedListToBST(ListNode* head) {
24+
auto curr = head;
25+
int n = 0;
26+
while (curr) {
27+
curr = curr->next;
28+
++n;
29+
}
30+
return BuildBSTFromSortedDoublyListHelper(&head, 0, n);
31+
}
32+
33+
TreeNode * BuildBSTFromSortedDoublyListHelper(ListNode **head, int s, int e) {
34+
if (s == e) {
35+
return nullptr;
36+
}
37+
38+
int m = s + ((e - s) / 2);
39+
auto left = BuildBSTFromSortedDoublyListHelper(head, s, m);
40+
auto curr = new TreeNode((*head)->val);
41+
42+
*head = (*head)->next;
43+
curr->left = left;
44+
curr->right = BuildBSTFromSortedDoublyListHelper(head, m + 1, e);
45+
return curr;
46+
}
47+
};

0 commit comments

Comments
 (0)