Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e4e2237

Browse files
Create BalancedBinaryTrees
1 parent 4daabdd commit e4e2237

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

‎Dynamic Programming/BalancedBinaryTrees

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include<iostream>
2+
#include<cmath>
3+
using namespace std;
4+
int balancedBTs_3(int n){
5+
int *ans=new int[n+1];
6+
int mod=(int)pow(10,9)+7;
7+
ans[0]=1;
8+
ans[1]=1;
9+
for(int i=2;i<=n;i++){
10+
ans[i]=(ans[i-1]*((2*ans[i-2])%mod+ans[i-1])%mod)%mod;
11+
}
12+
return ans[n];
13+
}
14+
int balancedBTs_helper(int h,int*ans){
15+
if(h<=1){
16+
return 1;
17+
}
18+
if(ans[h]!=-1){
19+
return ans[h];
20+
}
21+
int mod=(int) (pow(10,9))+7;
22+
int x=balancedBTs_helper(h-1,ans);
23+
int y=balancedBTs_helper(h-2,ans);
24+
int temp1=(int)(((long)(x)*x)%mod);
25+
int temp2=(int)((2*(long)(x)*y)%mod);
26+
int output=(temp1+temp2)%mod;
27+
ans[h]=output;
28+
return ans[h];
29+
30+
}
31+
int balancedBTs_2(int h){
32+
int *ans=new int[h+1];
33+
for(int i=0;i<=h;i++){
34+
ans[i]=-1;
35+
}
36+
return balancedBTs_helper(h,ans);
37+
}
38+
int balancedBTs(int h){
39+
if(h<=1){
40+
return 1;
41+
}
42+
int mod=(int) (pow(10,9))+7;
43+
int x=balancedBTs(h-1);
44+
int y=balancedBTs(h-2);
45+
int temp1=(int)(((long)(x)*x)%mod);
46+
int temp2=(int)((2*(long)(x)*y)%mod);
47+
int ans=(temp1+temp2)%mod;
48+
//int ans=(x*x+2*x*y)%mod;
49+
return ans;
50+
}
51+
int main(){
52+
int h;
53+
cin>>h;
54+
cout<<balancedBTs_3(h)<<endl;
55+
56+
57+
return 0;
58+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /