AlgoMaster Logo

Unique Binary Search Trees II

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Approach

Intuition:

The problem requires generating all unique binary search trees (BSTs) that store values 1 to n. The strategy hinges on picking each number as a root and recursively constructing all possible left and right subtrees.

The problem can be divided as follows:

  • Choose each number i from 1 to n to serve as the root.
  • The left subtree will consist of nodes from 1 to i-1.
  • The right subtree will consist of nodes from i+1 to n.
  • Recursively generate all unique BSTs for these left and right subtrees, and combine them to form the required trees.

Code:

2. Dynamic Programming Approach

Intuition:

Instead of recalculating solutions for the same subproblems multiple times, we can use a dynamic programming strategy to store results of previously solved problems in a memoization form. This helps reduce redundant computations but is more complex to set up and typically provides similar time complexity benefits for this specific problem.

Code: