-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05-KthLargestInBST.cpp
66 lines (61 loc) · 1.61 KB
/
05-KthLargestInBST.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
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
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) {}
};
// return the Kth largest element in the given BST rooted at 'root'
class Solution
{
public:
// Brute Force : inorder and reverse the vector ->
// O(nlogn) and O(h)
void inorder(TreeNode* root,vector<int> & v)
{
if(root==NULL)
{
return ;
}
if(root->left!=NULL)
inorder(root->left,v);
v.push_back(root->val);
if(root->right!=NULL)
inorder(root->right,v);
}
int kthLargest(TreeNode *root, int K)
{
vector<int> v;
inorder(root,v);
int n=v.size();
sort(v.begin(),v.end(),greater<int>());
return v[K-1];
}
// optimal -> O(h+k) and O(h)
void solve2(TreeNode* root,int k,int &cnt,int &res)
{
if(root->right!=NULL)
solve2(root->right,k,cnt,res);
cnt=cnt+1;
if(cnt==k)
{
res=root->val;
// cout<<res<<endl;
// return;
}
if(root->left!=NULL)
solve2(root->left,k,cnt,res);
}
int kthLargest2(TreeNode *root, int K)
{
int cnt=0;
int res=-1;
solve2(root,K,cnt,res);
return res;
}
};