Unique Binary Search Trees Leetcode Solution

In this post, you will know how to solve the Unique Binary Search Trees Leetcode Solution problem of Leetcode. This Leetcode problem is done in many programming languages like C++, Java, and Python.

Unique Binary Search Trees Leetcode Solution
Unique Binary Search Trees Leetcode Solutions

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Leetcode by yourself. If you find any difficulty after trying several times, then you can look for solutions.

Problem

Given an integer n, return the number of structurally unique BST’s (binary search trees) which has exactly n nodes of unique values from 1 to n.

Example 1:

Input: n = 3
Output: 5

Example 2:

Input: n = 1
Output: 1

Constraints:

  • 1 <= n <= 19

Unique Binary Search Trees Leetcode Solutions in Python

class Solution:
  def numTrees(self, n: int) -> int:
    # G[i] := # Of unique BST's that store values 1..i
    G = [1, 1] + [0] * (n - 1)
    for i in range(2, n + 1):
      for j in range(i):
        G[i] += G[j] * G[i - j - 1]
    return G[n]

Unique Binary Search Trees Leetcode Solutions in CPP

class Solution {
 public:
  int numTrees(int n) {
    // G[i] := # of unique BST's that store values 1..i
    vector<int> G(n + 1);
    G[0] = 1;
    G[1] = 1;
    for (int i = 2; i <= n; ++i)
      for (int j = 0; j < i; ++j)
        G[i] += G[j] * G[i - j - 1];
    return G[n];
  }
};

Unique Binary Search Trees Leetcode Solutions in Java

class Solution {
  public int numTrees(int n) {
    // G[i] := # of unique BST's that store values 1..i
    int[] G = new int[n + 1];
    G[0] = 1;
    G[1] = 1;
    for (int i = 2; i <= n; ++i)
      for (int j = 0; j < i; ++j)
        G[i] += G[j] * G[i - j - 1];
    return G[n];
  }
}

Note: This problem Unique Binary Search Trees is generated by Leetcode but the solution is provided by Brokenprogrammers. This tutorial is only for Educational and Learning purposes.

next: Unique Binary Search Trees II Leetcode Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *