Unique Binary Search Trees II

Medium

Description

Given an integer n, return all the structurally unique BST's which has exactly n nodes of unique values from 1 to n.

Examples

Input:n = 3
Output:[[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
Explanation:

All 5 unique BSTs.

Input:n = 1
Output:[[1]]
Explanation:

When n = 1, there is only one node with value 1, so there's exactly one possible BST structure - a single node tree.

Input:n = 2
Output:[[1,null,2],[2,1]]
Explanation:

When n = 2, there are two possible BST structures: either 1 is the root with 2 as right child, or 2 is the root with 1 as left child. Both are valid BSTs using nodes 1 and 2.

Constraints

  • 1 ≤ n ≤ 8

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!