Last Updated: 5 Jan, 2021

Find K-th smallest Element in BST

Easy
Asked in companies
SAP LabsGoldman SachsVisa

Problem statement

Given a binary search tree and an integer ‘K’. Your task is to find the ‘K-th’ smallest element in the given BST( binary search tree).

BST ( binary search tree) -

If all the smallest nodes on the left side and all the greater nodes on the right side of the node current node.

Example -

alt text

Order of elements in increasing order in the given BST is - { 2, 3, 4, 5, 6, 7, 8, 10 }

Suppose given ‘K = 3’ then 3rd smallest element is ‘4’.

Suppose given ‘K = 8’ then 8th smallest element is ‘10’.

Note:
1. You are not required to print the output explicitly, it has already been taken care of. Just implement the function and return the ‘K-th’ smallest element of BST.
2. You don’t need to return ‘K-th’ smallest node, return just value of that node. 
3. If ‘K-th’ smallest element is not present in BST then return -1.
Input Format:
The first line of input contains an integer ‘T’ denoting the number of test cases.
The next ‘T’ lines represent the ‘T’ test cases.

The first line of input contains a single integer ‘K’.
The second line of input contains the elements of the tree in the level order form separated by a single space.   
If any node does not have a left or right child, take -1 in its place. Refer to the example below.

Example:

Elements are in the level order form. The input consists of values of nodes separated by a single space in a single line. In case a node is null, we take -1 in its place.

For example, the input for the tree depicted in the below image would be :

alt text

1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1

Explanation :
Level 1 :
The root node of the tree is 1

Level 2 :
Left child of 1 = 2
Right child of 1 = 3

Level 3 :
Left child of 2 = 4
Right child of 2 = null (-1)
Left child of 3 = 5
Right child of 3 = 6

Level 4 :
Left child of 4 = null (-1)
Right child of 4 = 7
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 6 = null (-1)
Right child of 6 = null (-1)

Level 5 :
Left child of 7 = null (-1)
Right child of 7 = null (-1)

The first not-null node (of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.

The input ends when all nodes at the last level are null (-1).
Note :
The above format was just to provide clarity on how the input is formed for a given tree. 

The sequence will be put together in a single line separated by a single space. Hence, for the above-depicted tree, the input will be given as:

1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output Format:
For every test case, return the ‘K-th’ smallest element.
Constraint :
1 <= T <= 100
1 <= N, K <= 3000
-10^9 <= data <= 10^9

Where ‘T’ represents the number of test cases, ‘N’ is the number of nodes in the tree, ‘K’ denotes given integer and ‘data’ denotes data contained in the node of a binary tree.

Time Limit: 1 sec

Approaches

01 Approach

The basic idea is that traversal the whole tree in an inorder manner and adds the node values in an array and at the end return the ‘k-1’th element of the array. Due to BST property, inorder traversal of BST will in a sorted order( ascending ).

 

Code -

  • Initialize a global array ‘arr’, which stores the elements of the BST.
  • Use an ‘inorder(root)’ recursive function, to add all the child node in ‘arr’
    • First call ‘inorder(root->left)’.
    • Add the current node in ‘arr’.
    • Call the ‘inorder(root->right)’.
  • At the end return ‘arr[K-1]’.
  • If K is greater than length arr then return ‘-1’.

02 Approach

The basic idea is that traversal the tree in an inorder manner with help of iteration, so we don’t need a size ‘n’ call stack( call stack required to store all the calls from a function that is currently executing). But in an iterative manner, we can optimize it in O(H) space.  

 

Code -

  • Use a stack data-structure to implement it. And called it ‘stack’.
  • At every point in time, the current node is ‘root’.
  • Put the current node in ‘stack’, iterate the ‘current node = current node -> left’ until it is not ‘null/None’.
  • Now the current node is ‘null/None’ and ‘stack’ is not empty.
    • Pop the top element of ‘stack’ call it ‘root’, and decrease ‘K = K-1’
      • If ‘K’ is ‘0’ then return the current node’s value, because every time we are removing the element in sorted order( ascending ).
      • Make ‘root = root->right’.
      • Else repeat the above step.
  • If the stack is empty and ‘K’ is not ‘0’ then return ‘-1’.

03 Approach

In this approach, we will use the Morris traversal algorithm, which is the space optimization of approach-2.

 

Example -

  • Consider this binary search tree:
    5
   / \
  3   7
 / \   \
2   4   9
       /
      8
  • Currently node ‘5’ is the root, node ‘3’ is left subtree, so find the rightmost node of node ‘3’ and the rightmost node is node ‘4’.
  • Build a connection between node ‘4’ and root node ‘5’, ‘rightmost node->right = root node’.
  • And break the connection between ‘5’ and node ‘3’.
  • ‘root->left = null’.
  • The current new root is node ‘3’.
  3
 / \
2   4
     \
      5
       \
        7
         \
         9
        /
       8
  • Repeat the same process now BST will look like this.
2
 \
  3
   \
    4
     \
      5
       \
        7
         \
         9
        /
       8
  • Now node ‘2’ has no left subtree, so the first element of in-order traversal will be ‘2’ and proceed the same step.
  • { 2, 3, 4, 5, 7, 8, 9 }.

Pseudo Code -

  • Initialize current as root.
  • While current is not ‘null/None’
    • If current does not have left child
      • Decrease ‘K= K-1’
        • If ‘K == 0’ then return the current node value. ( current.data ).
      • Go to the right subtree, ‘current = current -> right’.
    • Else
      • In the current’s left subtree
        • Assign current as a right child of the rightmost child node.
      • Go to this left child, ‘current = current-> left’.
  • After traversing the whole BST, and ‘K’ is not ‘0’ then return ‘-1’.