快来看_两小程序几乎一样_但结果不一样_火眼金睛找不同呀

prosolve 2012-03-27 11:25:40
各位大神帮忙找一下区别吧,程序A(我写的)超时,程序B通过,代码如下:
A:

#include<stdlib.h>
#include<stdio.h>
struct info
{
int num;
struct info *l;
struct info *r;
};
void deep(struct info *p)
{
if(p!=NULL)
{
printf("%d",p->num);
if(p->l)
{
printf(" ");
deep(p->l);
}
if(p->r)
{
printf(" ");
deep(p->r);
}
}
}
main()
{
int c,n,root,a,b,i;
struct info t[25];
scanf("%d",&c);
while(c--)
{
for(i=0;i<25;i++)
{
t[i].num=i;
t[i].l=NULL;
t[i].r=NULL;
}
scanf("%d",&n);
scanf("%d",&root);
n--;
while(n--)
{
scanf("%d %d %d",&a,&b,&c);
if(c==0)
{
t[a].l=&t[b];
}
else
t[a].r=&t[b];
}
struct info *q=&t[root];
deep(q);
printf("\n");
}
// system("pause");
}

B:

#include<stdlib.h>
#include<stdio.h>

typedef struct node
{
int num;
struct node *left;
struct node *right;
}node, *nodelist;

void deep(node *N)
{
if (N != NULL)
{
printf("%d", N->num);
if (N->left)
{
printf(" ");
deep(N->left);
}
if (N->right)
{
printf(" ");
deep(N->right);
}
}
}

main()
{
int t, n, r;
int a, b, c;
int i;
node tree[25];
int top;

scanf("%d", &t);

while (t--)
{
for (i = 0; i < 25; i++)
{
tree[i].num = i;
tree[i].left = tree[i].right =NULL;
}
scanf("%d", &n);
scanf("%d", &r);
n--;
while (n--)
{

scanf("%d %d %d", &a, &b, &c);
if (c)
tree[a].right = &tree[b];
else
tree[a].left = &tree[b];
}
nodelist p = &tree[r];
deep(p);
printf("\n");
}
// system("pause");
}

题目如下:
Description
给定一棵有n个结点的二叉树,结点的编号为0~n-1。请你编写程序输出二叉树的前序遍历序列。

Input
输入的第一行是一个正整数t(1 < t < 20),表示有t组测试用例。
对于每组测试用例,第一行是一个整数n(0 < n < 20),表示二叉树结点个数。第二行是一个数r(0≤r≤n-1),二叉树根结点的编号。
后面有n-1行,表示二叉树n-1条边的信息。每行三个数a,b,c,三个数间由空格隔开,其中0≤a,b≤n-1且a≠b, c为0或1。a表示边的起点,b表示边的终点。如果c为0,表示b是a的左儿子;如果c为1,表示b是a的右儿子。

Output
对于每组测试用例输出一行,即:该二叉树的前序遍历序列,两个节点编号之间留一个空格。

Sample Input

2
3
2
2 0 0
2 1 1
7
0
0 1 0
0 2 1
1 3 0
1 4 1
2 5 0
2 6 1

Sample Output

2 0 1
0 1 3 4 2 5 6
...全文
193 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
relaxisland 2012-03-28
  • 打赏
  • 举报
回复
抄的挺好的啊
不过

while(c--)
{
跟后面的
scanf("%d %d %d", &a, &b, &c); 用同一个变量
c 就不能到0 了
prosolve 2012-03-28
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 relaxisland 的回复:]

抄的挺好的啊
不过

while(c--)
{
跟后面的
scanf("%d %d %d", &a, &b, &c); 用同一个变量
c 就不能到0 了
[/Quote]
三楼说的对呀,平时变量都是随意写的,看来这样真容易出问题,今后我一定会注意的。
对了,灰常感谢呀
_Minzey 2012-03-28
  • 打赏
  • 举报
回复
对啊,你用变量 c 判断while循环,后面又重新输入改变了 c 的值,循环什么时候结束变成未知了;还有,
程序A里面 if(c == 0),在程序B里面变成 if(c),一个判断假,一个判断真,下面执行的语句却是一样的?
simplecao2012 2012-03-27
  • 打赏
  • 举报
回复
mark,我是来学习的。
prosolve 2012-03-27
  • 打赏
  • 举报
回复
今晚不睡了,等大侠帮忙

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧