BSTKTHMAX - Editorial

Prerequisites :- Binary Search Trees, BT traversals.

Problem :- Given a binary search tree and an integer K, find the Kth largest node in it.

Solution Approach :-

To find the Kth largest element in a Binary Search Tree (BST), we can perform a reverse inorder traversal while maintaining a count of visited nodes. This approach takes advantage of the fact that reverse inorder traversal of a BST traverses nodes in descending order.

Algorithm :-

    1. Initialize a counter variable to keep track of the number of nodes visited.
    1. Perform a reverse inorder traversal (right, root, left):
      • Traverse the right subtree.
      • Visit the current node.
      • Traverse the left subtree.
    1. At each step of the traversal, decrement the K value.
    1. When the counter becomes equal to K, stop the traversal and print the value of the current node as it represents the Kth largest element.

Time complexity :- O(N), because in the worst case, the algorithm visits all the nodes in the given BST.

Space complexity :- O(1), as no extra space is needed.