#include <bits/stdc++.h>
using namespace std;
// tree node is defined
class TreeNode
{
public:
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int data)
{
val = data;
left = NULL;
right = NULL;
}
};
// reverse inorder traversal to find kth maximum element
void kthLargestRec(TreeNode *root, int K, int &count, int &ans)
{
if (!root)
return;
// reach the maximum node first doing reverse inorder traversal
kthLargestRec(root->right, K, count, ans);
// increment count
count++;
if (count == K)
{ // if it's K then the current node value is kth maximum
ans = root->val;
return;
}
kthLargestRec(root->left, K, count, ans);
}
// return the Kth largest element in the given BST rooted at 'root'
int kthLargest(TreeNode *root, int K)
{
// Your code here
int ans = INT_MAX;
int count = 0;
kthLargestRec(root, K, count, ans);
return ans;
}
int main()
{
TreeNode *root = new TreeNode(16);
root->left = new TreeNode(3);
root->left->right = new TreeNode(13);
root->left->right->left = new TreeNode(10);
root->right = new TreeNode(20);
root->right->left = new TreeNode(18);
int k = 3;
cout << "3rd maximum is: " << kthLargest(root, k) << endl;
k = 5;
cout << "5th maximum is: " << kthLargest(root, k) << endl;
return 0;
}
Output
3rd maximum is: 16
5th maximum is: 10
0 Comments