-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathKth_largest_element_in_BST.cpp
56 lines (46 loc) · 1.1 KB
/
Kth_largest_element_in_BST.cpp
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
/*
Problem Statement:
-----------------
Given a Binary search tree. Your task is to complete the function which will return the Kth largest element without doing any modification in Binary Search Tree.
Example 1:
---------
Input:
4
/ \
2 9
k = 2
Output: 4
Example 2:
---------
Input:
9
\
10
K = 1
Output: 10
Your Task: You don't need to read input or print anything. Your task is to complete the function kthLargest() which takes the root of the BST
and an integer K as inputs and returns the Kth largest element in the given BST.
Expected Time Complexity: O(H + K).
Expected Auxiliary Space: O(H)
*/
// Link --> https://practice.geeksforgeeks.org/problems/kth-largest-element-in-bst/1#
// Code:
class Solution
{
public:
vector <int> in;
void inorder(Node *root)
{
if(root == NULL)
return;
inorder(root->left);
in.push_back(root->data);
inorder(root->right);
}
int kthLargest(Node *root , int k)
{
in.clear();
inorder(root);
return in[in.size()-k];
}
};