Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Floor in BST

Moderate
0/80
Average time to solve is 30m
65 upvotes
Asked in companies
InfosysVirsoftech Private Limited

Problem statement

You are given a BST (Binary search tree) with’ N’ number of nodes and a value ‘X’. Your task is to find the greatest value node of the BST which is smaller than or equal to ‘X’.

Note :‘X’ is not smaller than the smallest node of BST .

For example:

1

In the above example, For the given BST  and X = 7, the greatest value node of the BST  which is smaller than or equal to  7 is 6.
Detailed explanation ( Input/output format, Notes, Images )
Constraints:
1 <= T <= 5
1 <= N <= 5 * 10 ^ 3
1 <= nodeVal[i] <= 10 ^ 9

Time Limit: 1 sec.
Sample Input 1:
2
10 5 15 2 6 -1 -1 -1 -1 -1 -1
7
2 1 3 -1 -1 -1 -1
2
Sample Output 1:
6
2
Explanation of Sample Input 1:
In the first test case, the BST looks like as below:

1

The greatest value node of the BST which is smaller than or equal to  7 is 6.

In the second test case, the BST looks like as below:

1

The greatest value node of the BST which is smaller than or equal to  2 is 2.
Sample Input 2:
2
5 3 10 2 4 6 15 -1 -1 -1 -1 -1 -1 -1 -1
15
5 3 10 2 4 6 15 -1 -1 -1 -1 -1 -1 -1 -1
8
Sample Output 2:
15
6
Full screen
Console