uva 699

这个牵扯到二叉树的简单操作吧,下附代码:

#include <stdio.h>

#include <malloc.h>
typedef struct node{
int value;
struct node *left;
struct node *right;
}node;
int output[200]={0};
node *creat()
{
int temp;
if(scanf("%d",&temp)==1)
{
if(temp!=-1)
{
node *tnode;
tnode=(node *)malloc(sizeof(node));
tnode->value=temp;
tnode->left=creat();
tnode->right=creat();
return tnode;
}
else{
return NULL;
}
}
}
void print(node *tnode)
{
if(tnode!=NULL)
{
printf("node : %d\n",tnode->value);
print(tnode->left);
print(tnode->right);
}
else return;
}
void preorder(node *tnode,int position)
{
if(tnode!=NULL)
{
output[position]+=tnode->value;
preorder(tnode->left,position-1);
preorder(tnode->right,position+1);
}
else return;
}
void print2()
{
int mark=0;
for(int i=0;i<200;i++)
{
if(output[i]!=0&&mark==0)
{
printf("%d",output[i]);
mark=1;
}
else if(output[i]!=0&&mark==1)
{
printf(" %d",output[i]);
}
}
printf("\n");
}
int main(int argc, char *argv[])
{
int num=0,markline=1;
int position=100;
freopen("data.in","r",stdin);
node *root;
root=creat();
while(root!=NULL)
{//print(root);
preorder(root,position);
//if(markline==1)
//{
// markline=0;
//}
// else{
// printf("\n");
//}
printf("Case %d:\n",++num);
print2();
printf("\n");
for(int loop=0;loop<200;loop++)
output[loop]=0;
root=creat();}
return 0;

}

以及样例数据(很重要):

5 7 -1 6 -1 -1 3 -1 -1


8 2 9 -1 -1 6 5 -1 -1 12 -1
-1 3 7 -1 -1 -1


14 12 5 7 -1 -1 -1 2 3 -1 -1 4 -1 -1 1 2 11 -1 22 -1 -1 -1 3 -1 1 2 -1 -1 -1


1 3 4 -1 5 6 -1 2 -1 -1 2 -1 -1 -1 -1


-1

output:

Case 1:
7 11 3


Case 2:
9 7 21 15


Case 3:
7 5 26 40 5 5 1


Case 4:
10 10 3



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值