-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path109. Convert Sorted List to Binary Search Tree 11 march
77 lines (67 loc) · 2.08 KB
/
109. Convert Sorted List to Binary Search Tree 11 march
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
// Finds the middle of the linked list
ListNode *middleNode(ListNode *head)
{
ListNode *slow = head, *fast = head;
while (fast and fast->next)
slow = slow->next, fast = fast->next->next;
return slow;
}
TreeNode *build(ListNode *head)
{
// If the list is empty then return null
if (!head)
return NULL;
// If the list contains only one element then return TreeNode of that value
if (middleNode(head) == head)
return new TreeNode(head->val);
// Finding the middle node
ListNode *middle = middleNode(head);
// Making middle node as root
TreeNode *root = new TreeNode(middle->val);
// Dividing list into to parts
// 1. Left part will have elements which is left to 'middle' node
// 2. Right part will have elements which is right to 'middle' node
ListNode *ptr = head;
while (ptr->next != middle)
ptr = ptr->next;
ListNode *first = head;
ListNode *second = middle->next;
// Removing middle from the list
ptr->next = NULL;
middle->next = NULL;
// building BST recursively
root->left = build(first);
root->right = build(second);
// returning root
return root;
}
TreeNode *sortedListToBST(ListNode *head)
{
if (!head)
return NULL;
return build(head);
}
};