Unique Binary Search Trees In C,CPP,JAVA,PYTHON,C#,JS
Problem Statement: Unique Binary Search Trees (BSTs) using DP Given a number n, return the total number of unique binary search trees (BSTs) that can be constructed using values 1 through n. The problem is asking for the number of structurally unique BSTs that can be built from n distinct nodes. Example: Time and Space Complexity: Approach: Algorithm: Code Implementation in Multiple Languages: 1. C: #include <stdio.h>int numTrees(int n) { if (n == 0 || n == 1) return 1; int dp[n + 1]; dp[0] = dp[1] = 1; for (int i = 2; i <= n; i++) { dp[i] = 0; for (int j = 1; j <= i; j++) { dp[i] += dp[j – 1] * dp[i – j]; } } return dp[n];}int main() { int n = 3; printf(“Number of unique BSTs with %d nodes: %d\n”, n, numTrees(n)); return 0;} 2. C++: #include <iostream>#include <vector>using namespace std;int numTrees(int n) { if (n == 0 || n == 1) return 1; vector<int> dp(n + 1, 0); dp[0] = dp[1] = 1; for (int i = 2; i <= n; i++) { for (int j = 1; j <= i; j++) { dp[i] += dp[j – 1] * dp[i – j]; } } return dp[n];}int main() { int n = 3; cout << “Number of unique BSTs with ” << n << ” nodes: ” << numTrees(n) << endl; return 0;} 3. Java: public class Solution { public int numTrees(int n) { if (n == 0 || n == 1) return 1; int[] dp = new int[n + 1]; dp[0] = dp[1] = 1; for (int i = 2; i <= n; i++) { for (int j = 1; j <= i; j++) { dp[i] += dp[j – 1] * dp[i – j]; } } return dp[n]; } public static void main(String[] args) { Solution solution = new Solution(); int n = 3; System.out.println(“Number of unique BSTs with ” + n + ” nodes: ” + solution.numTrees(n)); }} 4. Python: def numTrees(n: int) -> int: if n == 0 or n == 1: return 1 dp = [0] * (n + 1) dp[0] = dp[1] = 1 for i in range(2, n + 1): for j in range(1, i + 1): dp[i] += dp[j – 1] * dp[i – j] return dp[n]# Example usage:n = 3print(f”Number of unique BSTs with {n} nodes: {numTrees(n)}”) 5. C#: using System;public class Solution { public int NumTrees(int n) { if (n == 0 || n == 1) return 1; int[] dp = new int[n + 1]; dp[0] = dp[1] = 1; for (int i = 2; i <= n; i++) { for (int j = 1; j <= i; j++) { dp[i] += dp[j – 1] * dp[i – j]; } } return dp[n]; } public static void Main(string[] args) { Solution solution = new Solution(); int n = 3; Console.WriteLine($”Number of unique BSTs with {n} nodes: {solution.NumTrees(n)}”); }} 6. JavaScript: function numTrees(n) { if (n === 0 || n === 1) return 1; const dp = Array(n + 1).fill(0); dp[0] = dp[1] = 1; for (let i = 2; i <= n; i++) { for (let j = 1; j <= i; j++) { dp[i] += dp[j – 1] * dp[i – j]; } } return dp[n];}// Example usage:let n = 3;console.log(`Number of unique BSTs with ${n} nodes: ${numTrees(n)}`); Explanation of the Code: Example Output: For n = 3, the output will be: Number of unique BSTs with 3 nodes: 5 Each of the implementations will compute the same result using dynamic programming.
Unique Binary Search Trees In C,CPP,JAVA,PYTHON,C#,JS Read More »