Find k | A BST node ; Recursive function to insert an key into BST ; Function to find k 'th largest element in BST. Here count denotes the number of nodes processed so far ; Base case ; Search in left subtree ; If k 'th smallest is found in  left subtree, return it ; If current element is k 'th  smallest, return it ; Else search in right subtree ; Function to find k 'th largest element in BST ; Maintain index to count number of nodes processed so far ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return Node ( x ) NEW_LINE DEDENT if ( x < root . data ) : NEW_LINE INDENT root . left = insert ( root . left , x ) NEW_LINE DEDENT elif ( x > root . data ) : NEW_LINE INDENT root . right = insert ( root . right , x ) NEW_LINE DEDENT return root NEW_LINE DEDENT def kthSmallest ( root ) : NEW_LINE INDENT global k NEW_LINE if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT left = kthSmallest ( root . left ) NEW_LINE if ( left != None ) : NEW_LINE INDENT return left NEW_LINE DEDENT k -= 1 NEW_LINE if ( k == 0 ) : NEW_LINE INDENT return root NEW_LINE DEDENT return kthSmallest ( root . right ) NEW_LINE DEDENT def printKthSmallest ( root ) : NEW_LINE INDENT count = 0 NEW_LINE res = kthSmallest ( root ) NEW_LINE if ( res == None ) : NEW_LINE INDENT print ( " There ▁ are ▁ less ▁ than ▁ k ▁ nodes ▁ in ▁ the ▁ BST " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " K - th ▁ Smallest ▁ Element ▁ is ▁ " , res . data ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE keys = [ 20 , 8 , 22 , 4 , 12 , 10 , 14 ] NEW_LINE for x in keys : NEW_LINE INDENT root = insert ( root , x ) NEW_LINE DEDENT k = 3 NEW_LINE printKthSmallest ( root ) NEW_LINE DEDENT