101 Logo
onenoughtone

Problem Statement

Tree Structure Counter

You're a data scientist working on a tree visualization project. You need to determine how many different ways you can structure a binary search tree (BST) with n nodes.

In a binary search tree:

  • Each node has a unique value from 1 to n
  • The left subtree of a node contains only nodes with values less than the node's value
  • The right subtree of a node contains only nodes with values greater than the node's value

Your task is to calculate the total number of structurally unique BSTs that can be formed with n nodes labeled from 1 to n.

For example, with n = 3, there are 5 unique BST structures that can be formed.

Examples

Example 1:

Input: n = 3
Output: 5
Explanation: There are 5 structurally unique BSTs with 3 nodes: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3

Example 2:

Input: n = 1
Output: 1
Explanation: There is only one BST with 1 node, which is the node itself.

Constraints

  • 1 <= n <= 19

Problem Breakdown

To solve this problem, we need to:

  1. The number of unique BSTs depends only on the number of nodes, not their specific values
  2. We can use the property that any node can be the root of the BST
  3. For each root value i, the left subtree contains values 1 to i-1, and the right subtree contains values i+1 to n
  4. The total number of BSTs with root i is the product of the number of possible left subtrees and right subtrees
  5. This problem has optimal substructure, making it suitable for dynamic programming
  6. The solution is related to Catalan numbers, a sequence that appears in many combinatorial problems
ProblemSolutionCode
101 Logo
onenoughtone