![]() |
VOOZH | about |
Given a Binary Search Tree (BST) and a positive integer k, the task is to find the kth largest element in the Binary Search Tree.
Example:
Input: k = 3
π th-Largest-element-in-BSTOutput: 14
Explanation: If we sort the BST in decreasing order, then it will become 22, 20, 14, 12, 10, 8, 4. 14 is the 3rd largest element.
Table of Content
The idea is to traverse the binary search tree in reverse in-order manner. This way we will traverse the elements in decreasing order. Maintain the count of nodes traversed so far. If count becomes equal to k, return the element.
14
The idea is to similar to recursion, but in this method, stack will be used to traverse the binary search tree in reverse in-order manner. This way we will traverse the elements in decreasing order. Maintain the count of nodes traversed so far. If count becomes equal to k, return the element.
Below is the implementation of the above approach:
14
The idea is to use Reverse Morris Traversal Algorithm to traverse the binary search tree in reverse in-order manner and maintain the count of nodes traversed so far. If number of nodes traversed become equal to k, then return the node. Please refer to Kβth Largest element in BST using constant extra space for implementation.