有没有人能告诉我,我的代码到底错在哪
2026-07-16 13:33:49
发布于:浙江
58阅读
0回复
0点赞
#include<bits/stdc++.h>
using namespace std;
struct node{
int l,r;
};
int n;
node a[100010];
int cnt = 0;
int vis[100010];
void dfs( int idx ){
if ( a[idx].l == 0 && a[idx].r == 0 ){
cnt++;
return ;
}
if ( a[idx].l != 0 && vis[idx] != 1 ){
vis[idx] = 1;
dfs(a[idx].l);
vis[idx] = 0;
}
if ( a[idx].r != 0 && vis[idx] != 1 ){
vis[idx] = 1;
dfs(a[idx].r);
vis[idx] = 0;
}
}
int main(){
cin >> n;
for ( int i = 1; i <= n; i++ ){
cin >> a[i].l >> a[i].r;
}
vis[1] = 1;
dfs(1);
cout << cnt;
return 0;
}
全部评论 4
可以壶关吗?
昨天 来自 广东
2已关
昨天 来自 江苏
1刚看见
昨天 来自 江苏
1
代码在这里(模仿了你的马蜂):
#include<bits/stdc++.h> using namespace std; struct node{ int l,r,h;//加这里 }; int n; node a[100010]; //vis可以不用了 int cnt = 0; void dfs( int idx ){ if ( a[idx].l == 0 && a[idx].r == 0 ){ cnt++; a[idx].h = 1; return ; } if ( a[idx].l != 0){//只要有左子树就一定要 dfs dfs(a[idx].l); } if ( a[idx].r != 0){//同上 dfs(a[idx].r); } //判断条件也要改 //左子树和右子树不为零并且高度一致 //左右子树的的高度大于零是在判断左右子树是否为满二叉树 if ( a[idx].r != 0 && a[idx].l != 0 && a[a[idx].l].h == a[a[idx].r].h && a[a[idx].l].h > 0 && a[a[idx].r].h > 0){ cnt++; a[idx].h = a[a[idx].l].h+1; } else { a[idx].h = 0;//否则说明不是满二叉树,将高度置为0 } } int main(){ cin >> n; for ( int i = 1; i <= n; i++ ){ cin >> a[i].l >> a[i].r; } dfs(1); cout << cnt; return 0; }昨天 来自 广东
2有帮助,🦀🦀
昨天 来自 江苏
1
错的有点多,你忘记了一个重要的地方,左右子树的高度要一致,所以要在结构体里加一个 。
昨天 来自 广东
2菜鸟勿喷
昨天 来自 江苏
1
盆友,你这代码改死我了。。。
昨天 来自 广东
2s h i t山代码
昨天 来自 江苏
1









有帮助,赞一个