Skip to content

Commit f112c7e

Browse files
authored
Problem Difficulty Level: Medium
1 parent 03563d4 commit f112c7e

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*------------------------
2+
Time Complexity: O(n)
3+
Space Complexity: O(n)
4+
--------------------------*/
5+
6+
class Solution {
7+
public:
8+
TreeNode* constructTree(unordered_map<int, ListNode*> &listMapping, int low, int high){
9+
if(low > high) return NULL;
10+
11+
int mid = low + (high - low) / 2;
12+
ListNode* midNode = listMapping[mid];
13+
TreeNode* newNode = new TreeNode(midNode -> val);
14+
15+
newNode -> left = constructTree(listMapping, low, mid - 1);
16+
newNode -> right = constructTree(listMapping, mid + 1, high);
17+
return newNode;
18+
}
19+
20+
TreeNode* sortedListToBST(ListNode* head) {
21+
unordered_map<int, ListNode*> listMapping;
22+
ListNode* currNode = head;
23+
int index = 0;
24+
25+
while(currNode){
26+
listMapping[index] = currNode;
27+
currNode = currNode -> next;
28+
index += 1;
29+
}
30+
return constructTree(listMapping, 0, index - 1);
31+
}
32+
};
33+
34+
/*
35+
Question Link: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
36+
Author: M.R.Naganathan
37+
*/

0 commit comments

Comments
 (0)