-
Notifications
You must be signed in to change notification settings - Fork 0
/
BSTfromlinkedlist
46 lines (36 loc) · 925 Bytes
/
BSTfromlinkedlist
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
Node <int> * midelement(Node <int> * head)
{
if(head->next == NULL)
{
return head ;
}
Node <int> * slow = head ;
Node <int> * fast = head ;
Node <int> * prev = NULL ;
while(fast != NULL && fast->next != NULL)
{
prev = slow ;
slow = slow->next ;
fast = fast->next->next ;
}
prev->next = NULL ;
return slow;
}
TreeNode<int>* sortedListToBST(Node<int>* head)
{
if(head == NULL)
{
return NULL;
}
if(head->next == NULL)
{
TreeNode<int>* root = new TreeNode <int>(head->data) ;
return root ;
}
Node <int> * mid = midelement(head) ;
TreeNode<int>* root = new TreeNode <int>(mid->data) ;
root->left = sortedListToBST( head ) ;
root->right = sortedListToBST( mid->next) ;
return root ;
// Write your code here.
}