Find k | A simple inorder traversal based C # program to find k - th smallest element in a BST . ; 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 an index to count number of nodes processed so far ; Driver code
using System ; class Node { public int data ; public Node left , right ; public Node ( int x ) { data = x ; left = right = null ; } } class GFG { static int count = 0 ; public static Node insert ( Node root , int x ) { if ( root == null ) return new Node ( x ) ; if ( x < root . data ) root . left = insert ( root . left , x ) ; else if ( x > root . data ) root . right = insert ( root . right , x ) ; return root ; } public static Node kthSmallest ( Node root , int k ) { if ( root == null ) return null ; Node left = kthSmallest ( root . left , k ) ; if ( left != null ) return left ; count ++ ; if ( count == k ) return root ; return kthSmallest ( root . right , k ) ; } public static void printKthSmallest ( Node root , int k ) { count = 0 ; Node res = kthSmallest ( root , k ) ; if ( res == null ) Console . WriteLine ( " There ▁ are ▁ less ▁ " + " than ▁ k ▁ nodes ▁ in ▁ the ▁ BST " ) ; else Console . WriteLine ( " K - th ▁ Smallest " + " ▁ Element ▁ is ▁ " + res . data ) ; } public static void Main ( String [ ] args ) { Node root = null ; int [ ] keys = { 20 , 8 , 22 , 4 , 12 , 10 , 14 } ; foreach ( int x in keys ) root = insert ( root , x ) ; int k = 3 ; printKthSmallest ( root , k ) ; } }