-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindKthLargestElementInBST.cpp
More file actions
executable file
·155 lines (115 loc) · 2.17 KB
/
findKthLargestElementInBST.cpp
File metadata and controls
executable file
·155 lines (115 loc) · 2.17 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
// print the difference between odd Level and Even Level nodes in tree...
//
//
#include<iostream>
using namespace std;
typedef struct tnode
{
int data;
struct tnode *left;
struct tnode *right;
};
tnode* createNode(int num)
{
tnode *temp;
temp=(tnode*)malloc(sizeof(tnode));
temp->data=num;
temp->left=NULL;
temp->right=NULL;
return temp;
}
void inorder(tnode *root)
{
if(root==NULL)
return ;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
void preorder(tnode *root)
{
if(root==NULL)
return ;
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
void postorder(tnode *root)
{
if(root==NULL)
return ;
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
}
int height(tnode *root)
{
if(root==NULL)
return 0;
int lheight,rheight;
lheight=height(root->left);
rheight=height(root->right);
if(lheight>rheight)
return (lheight+1);
else
return (rheight+1);
}
int max(int a,int b,int c)
{
if(a>=b && a>=c)
return a;
if(b>=c && b>=a)
return b;
if(c>=a && c>=b)
return c;
}
void kLargestUtill(tnode* root,tnode* (&ans),int &count,int k)
{
if(root==NULL)
return ;
kLargestUtill(root->right,ans,count,k);
if(count==k)
{
ans=root;
count++;
}
else
count++;
kLargestUtill(root->left,ans,count,k);
}
tnode *kthLargest(tnode *root,int k)
{
if(root==NULL) // condition check...
{
return NULL;
}
tnode *ans=NULL;
int count=1;
kLargestUtill(root,ans,count,k);
return ans;
}
int main()
{
int wait;
tnode *root,*start;
root=createNode(5);
root->left=createNode(3);
root->right=createNode(7);
root->left->left=createNode(2);
root->left->right=createNode(4);
root->right->left=createNode(6);
root->right->right=createNode(8);
int k;
//inorder(root);
//cout<<endl;
cout<<"Enter k..."<<endl;
cin>>k;
start=kthLargest(root,k);
if(start)
cout<<k<<"th Largest Nodes value is "<<start->data<<endl;
else
cout<<"Less Number of nodes than k in tree..\n";
cout<<"Done..\n";
cin>>wait;
return 0;
}