
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Unique Binary Search Trees in C++
Suppose we have an integer n, we have to count all structurally unique binary search trees that store values from 1 to n. So if the input is 3, then the output will be 5, as the trees will be –
To solve this, we will follow these steps –
- create one array of size n + 1
- dp[0] := 1
- for i := 1 to n
- for j := 0 to i – 1
- dp[i] := dp[i] + (dp[i – 1 – j] * dp[j])
- for j := 0 to i – 1
- return dp[n]
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int numTrees(int n) { vector <int> dp(n+1); dp[0] = 1; for(int i =1;i<=n;i++){ for(int j = 0;j<i;j++){ //cout << j << " " << i-1-j << " " << j << endl; dp[i] += (dp[i-1-j] * dp[j]); } } return dp[n]; } }; main(){ Solution ob; cout << ob.numTrees(4); }
Input
4
Output
14
- Related Articles
- Unique Binary Search Trees II in C++
- Multidimensional Binary Search Trees
- All Elements in Two Binary Search Trees in C++
- Binary Search Trees in Data Structures
- Print Common Nodes in Two Binary Search Trees in C++
- Optimal Binary Search Trees in Data Structures
- Balanced binary search trees in Data Structure
- Count the Number of Binary Search Trees present in a Binary Tree in C++
- Merge Two Binary Trees in C++
- Flip Equivalent Binary Trees in C++
- Binary Trees With Factors in C++
- Enumeration of Binary Trees in C++
- Binary search in C#
- Binary Search in C++
- All Possible Full Binary Trees in C++

Advertisements