想要拿时间刺客的话就来看看
2026-08-27 11:33:04
发布于:广东
12阅读
0回复
0点赞
乍一眼看上去,我还以为和这题一样,把代码一贴,才看到题目是满二叉树。。。
然而满二叉树其实更简单。
题目中已经把满二叉树的定义给出来了,大家就自己去看吧。
当认真观察之后,我们可以由此得到两个结论:
一:叶子结点一定是满二叉树;
二:当前结点的左子树是满二叉树、右子树也是满二叉树,并且左右子树高一至时,当前结点所领导的子树一定是满二叉树。
然后就可以了。
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+9;
int l[N],r[N],h[N];
bool f[N];
int ans=0;
void dfs(int p){
if(l[p]==0&&r[p]==0){
ans++,h[p]=1,f[p]=true;
return ;
}
if(l[p]!=0) dfs(l[p]);
if(r[p]!=0) dfs(r[p]);
int lx=l[p],rx=r[p];
if(lx!=0&&rx!=0&&f[lx]!=false&&f[rx]!=false&&h[lx]==h[rx]){
ans++;
f[p]=true;
h[p]=h[lx]+1;
}else{
f[p]=false;
h[p]=0;
}
}
int main(){
int n; cin>>n;
for(int i=1;i<=n;i++) cin>>l[i]>>r[i];
dfs(1);
cout<<ans;
return 0_0;
}
看到这里的你:等一下,你的题目是什么意思?
其实也没什么啦,加上快读,再关闭同步输入输出流就可以了。截止至本题解发布时是打败 100% 用户的状态。
贴上完整代码:
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+9;
int l[N],r[N],h[N];
bool f[N];
int ans=0;
inline int read() {
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9') {
if(ch=='-') f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9') {
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
void dfs(int p){
if(l[p]==0&&r[p]==0){
ans++,h[p]=1,f[p]=true;
return ;
}
if(l[p]!=0) dfs(l[p]);
if(r[p]!=0) dfs(r[p]);
int lx=l[p],rx=r[p];
if(lx!=0&&rx!=0&&f[lx]!=false&&f[rx]!=false&&h[lx]==h[rx]){
ans++;
f[p]=true;
h[p]=h[lx]+1;
}else{
f[p]=false;
h[p]=0;
}
}
int main(){
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n; n=read();
for(int i=1;i<=n;i++) l[i]=read(),r[i]=read();
dfs(1);
cout<<ans;
return 0_0;
}
要是复制题解就会 WA 哦~
这里空空如也







有帮助,赞一个