二叉树的遍历题目,数据读入有点麻烦,后来发现-1的个数比正数的个数多1的时候正好一棵树的数据就读完了,然后递归进行先序遍历,在遍历的过程中生成每一个正数节点的水平方向的坐标数值,假设一开始的根节点的坐标为0,遍历的过程中往左走坐标就减去1,往右走就加上1,然后进行适当的累加就行了。
#include <stdio.h>
#include <set>
#include <algorithm>
using namespace std;
struct node
{
int pos; //水平位置
int leaves; //叶子数量
bool operator < (const struct node &n) const
{
if(this->pos < n.pos)
return true;
else
return false;
}
};
#define MAX_LEN 2000
int buffer[MAX_LEN];
int result[MAX_LEN];
multiset<struct node> s;
int buffer_index;
int case_count;
//pos为水平的位置
void pre_travel(int pos)
{
int root_num;
root_num = buffer[buffer_index];
if(buffer[buffer_index] == -1)
return;
struct node n;
n.pos = pos;
n.leaves = buffer[buffer_index];
s.insert(n);
buffer_index++;
pre_travel(pos-1); //遍历左子树
buffer_index++;
pre_travel(pos+1); //遍历右子树
}
void func()
{
int i;
int sum;
int count;
multiset<struct node>::iterator it_i, it_j;
buffer_index = 0;
s.clear();
pre_travel(0); //假设root位置为0,向左坐标递减,向右坐标递增
count = 0;
for(it_i=s.begin(); it_i!=s.end(); )
{
sum = it_i->leaves;
for(it_j=++it_i, it_i--; it_j!=s.end(); it_j++)
{
if(it_j->pos == it_i->pos)
sum += it_j->leaves;
else
break;
}
result[count++] = sum;
if(it_j == s.end())
break;
it_i = it_j;
}
printf("Case %d:\n", case_count);
for(i=0; i<count-1; i++)
printf("%d ", result[i]);
printf("%d\n\n", result[i]);
}
int main(void)
{
int count, count_negative;
int num;
//freopen("input.dat", "r", stdin);
case_count = 0;
while(1)
{
count = 0;
count_negative = 0;
while(1)
{
scanf("%d", &num);
buffer[count++] = num;
if(num==-1)
{
count_negative ++;
if(count_negative == count/2+1)
break;
}
}
if(buffer[0]==-1)
break;
case_count ++;
func();
}
return 0;
}