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

Unique BSTs

Hard
0/120
Average time to solve is 50m
profile
Contributed by
3 upvotes
Asked in companies
AmazonMicrosoftGoogle

Problem statement

Ninja is learning DSA to perform well in his college exams. He is learning about binary search trees. After learning about the properties of BST, he is curious to know that how many BST can exist for a set of given numbers. He wants to know all the unique BST having exactly N values from 1 to N.Can you help Ninja to form all the unique BST?

You are given an integer ‘N’.Your task is to return the list of the root node of all the unique BST having values from 1 to N.

For Example
If N is 3,all unique BST will be:

Example

Detailed explanation ( Input/output format, Notes, Images )
Constraints:
1 <= N <= 8.

Time limit: 1 sec
Sample Input 1:
3
Sample Output 1:
1 -1 3 2 -1 -1 -1
1 -1 2 -1 3 -1 -1
2 1 3 -1 -1 -1 -1
3 2  -1 1 -1 -1 -1
3 1 -1 -1 2 -1 -1
Explanation of sample input 1:
For the first test case,

There exist 5 unique BST for the values 1 to 3. So, the given arrays are the level order traversal for each unique BST. (Empty Node is denoted by -1).

Example

Sample Input 2:
2
Sample Output 2:
1 -1 2 -1 -1
2 1 -1 -1 -1
Full screen
Console