Unique Binary Search Trees
To solve this coding challenge, we need to determine the number of structurally unique Binary Search Trees (BSTs) that can be formed using
nodes, where the nodes have unique values from 1 to
. The solution involves dynamic programming, which is a method for solving a complex problem by breaking it down into simpler subproblems and storing the results of these subproblems to avoid redundant calculations.
array, this method efficiently computes the desired result without redundant calculations.
n
n
Explanation
- Understanding the BST : A Binary Search Tree (BST) is a tree structure where each node has at most two children. The left child contains nodes with values less than the parent node, and the right child contains nodes with values greater than the parent node.
-
Unique BSTs
: For each node
i
n
i
i-1
i+1
n
- Dynamic Programming Approach :
-
We use a list
dp
dp[i]
i
-
Initialize
dp[0]
dp[1]
0
1
-
For
i
n
-
For each
j
i
-
Compute the number of unique BSTs for
i
j
-
The left subtree will have
j-1
i-j
-
Update
dp[i]
-
Result
: The result
dp[n]
n
-
Initialize a list
dp
n+1
-
Set
dp[0]
dp[1]
-
Loop through
i
n
-
For each
i
j
i
-
Calculate the number of trees with
i
j
-
Use the formula
dp[i] += dp[j-1] * dp[i-j]
-
Return
dp[n]
n
Step-by-Step Explanation
Initialization:
DP Iteration:
Result:
Pseudocode:
# Initialize the dp array with zeros and length n+1
dp = [0] * (n + 1)
# The number of BSTs with 0 or 1 node is 1
dp[0] = dp[1] = 1
# Start filling the dp array for i from 2 to n
for i in range(2, n + 1):
# For each number of nodes i, calculate the number of unique BSTs
for j in range(1, i + 1):
# dp[j-1] represents the number of unique BSTs with j-1 nodes (left subtree)
# dp[i-j] represents the number of unique BSTs with i-j nodes (right subtree)
dp[i] += dp[j - 1] * dp[i - j]
# Return the result stored in dp[n] which is the number of unique BSTs with n nodes
return dp[n]
The above pseudocode provides a method to calculate the number of unique BSTs using dynamic programming. It iterates over possible root nodes and combines the counts of unique BSTs for left and right subtrees. By storing intermediate results in the
dp