Unique Binary Search Trees @LeetCode
PROBLEM :
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :( Recursive Solution - Complexity O(2^n) )
--------------------------------------------------------------------------------
class Solution {
public:
int numTrees(int n) {
if(n==1||n==0)
return 1 ;
int leftTrees=0, rightTrees=0 ,Total=0 ;
for(int i=1;i<=n;i++){
leftTrees=numTrees(i-1) ;
rightTrees=numTrees(n-i) ;
Total=Total+(leftTrees*rightTrees) ;
}
return Total ;
}
};
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :( Iterative Solution - Complexity O(n^2))
--------------------------------------------------------------------------------
class Solution {
public:
int numTrees(int n) {
if(n==0||n==1)
return 1 ;
if(n==2)
return 2 ;
int arr[n+1] ;
arr[0]=1 ;
arr[1]=1 ;
arr[2]=2 ;
for(int i=3;i<=n;i++){
int sum=0 ;
for(int j=0;j<i;j++){
sum+=arr[j]*arr[i-j-1] ;
}
arr[i]=sum ;
}
return arr[n] ;
}
};
---------------------------------------------------------------------------------
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :( Recursive Solution - Complexity O(2^n) )
--------------------------------------------------------------------------------
class Solution {
public:
int numTrees(int n) {
if(n==1||n==0)
return 1 ;
int leftTrees=0, rightTrees=0 ,Total=0 ;
for(int i=1;i<=n;i++){
leftTrees=numTrees(i-1) ;
rightTrees=numTrees(n-i) ;
Total=Total+(leftTrees*rightTrees) ;
}
return Total ;
}
};
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :( Iterative Solution - Complexity O(n^2))
--------------------------------------------------------------------------------
class Solution {
public:
int numTrees(int n) {
if(n==0||n==1)
return 1 ;
if(n==2)
return 2 ;
int arr[n+1] ;
arr[0]=1 ;
arr[1]=1 ;
arr[2]=2 ;
for(int i=3;i<=n;i++){
int sum=0 ;
for(int j=0;j<i;j++){
sum+=arr[j]*arr[i-j-1] ;
}
arr[i]=sum ;
}
return arr[n] ;
}
};
---------------------------------------------------------------------------------
Comments
Post a Comment