forked from sarthakd999/Hacktoberfest2021-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST_max.c
82 lines (60 loc) · 1.55 KB
/
BST_max.c
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
78
79
80
81
82
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode(int data)
{
struct Node* temp = malloc(sizeof(struct Node));
temp->data = data;
temp->right = temp->left = NULL;
return temp;
}
struct Node* KthLargestUsingMorrisTraversal(struct Node* root, int k)
{
struct Node* curr = root;
struct Node* Klargest = NULL;
int count = 0;
while (curr != NULL) {
if (curr->right == NULL) {
if (++count == k)
Klargest = curr;
curr = curr->left;
}
else {
struct Node* succ = curr->right;
while (succ->left != NULL && succ->left != curr)
succ = succ->left;
if (succ->left == NULL) {
succ->left = curr;
curr = curr->right;
}
else {
succ->left = NULL;
if (++count == k)
Klargest = curr;
curr = curr->left;
}
}
}
return Klargest;
}
int main()
{
/* Constructed binary tree is
4
/ \
2 7
/ \ / \
1 3 6 10 */
struct Node* root = newNode(4);
root->left = newNode(2);
root->right = newNode(7);
root->left->left = newNode(1);
root->left->right = newNode(3);
root->right->left = newNode(6);
root->right->right = newNode(10);
printf("Finding K-th largest Node in BST : %d\n", KthLargestUsingMorrisTraversal(root, 3)->data);
return 0;
}