Kth Smallest element in a BST

Kth Smallest element in a BST

·

2 min read

Problem Statement

Note: Your solution should have only one BST traversal and O(1) extra space complexity, since this is what you will be asked to accomplish in an interview.

A tree is considered a binary search tree (BST) if for each of its nodes the following is true:

  1. The left subtree of a node contains only nodes with keys less than the node's key.

  2. The right subtree of a node contains only nodes with keys greater than the node's key.

  3. Both the left and the right subtrees must also be binary search trees.

Given a binary search tree t, find the k<sup>th</sup> smallest element in it.

Solution

Somehow it is intuitive that we should be using inorder traversal. We can keep a count variable to get the kth element while traversing the tree in inorder fashion.

Read out the comments in the below solution to understand better.

// we will call our function as KthSmallest(root, k, 0)

int KthSmallest(TreeNode root, int k, int count) {
    // if not found
    if(root==null)
        return -1;
    // Traverse the left subtree and check if kth element is found
    int left = KthSmallest(root.left, k, count);
    if(left!=-1)
        return left;
    // Increase the count, and check if the data(D) element is the ans (LDR)
    count++;
    if(count==k)
        return root.data;
    // Traverse the right subtree
    return KthSmallest(root.right, k, count);
}

Time Complexity of above code will be O(n) - where n is the number of nodes in the tree, and space complexity will be O(1) as we are not using any additional space.