-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0109.cpp
More file actions
executable file
·39 lines (33 loc) · 760 Bytes
/
LC0109.cpp
File metadata and controls
executable file
·39 lines (33 loc) · 760 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
Problem Statement: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
Time: O(n)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
private:
int length(ListNode* head) {
int len = 0;
while (head) {
len++;
head = head->next;
}
return len;
}
TreeNode* build(int low, int high, ListNode*& head) {
// base case
if (low > high)
return nullptr;
TreeNode *left, *right;
int mid = low + (high - low) / 2;
left = build(low, mid - 1, head);
int val = head->val;
head = head->next;
right = build(mid + 1, high, head);
return new TreeNode(val, left, right);
}
public:
TreeNode* sortedListToBST(ListNode* head) {
return build(0, length(head) - 1, head);
}
};