北郵12年網研 -二叉樹的層數

Description

老師有一個問題想考考mabo,但是mabo不會,所以想請你來幫幫忙。

問題如下:

給一個二叉樹

請把這個棵二叉樹按層來打印。如果爲相同層,需要從左到右打印。一個節點是先添加左節點後添加右節點,即添加順序與輸入順序一致。

Input

首先輸入一個整數T,表示一共有T組數據 0<T<=10

再輸入兩個整數N,M(0<=N,M<=100)

表示下面有N行,這個樹有M個節點(1號節點是這棵樹的根節點)

每一行兩個整數a,b(1<=a,b<=M)

表示節點a的父親是節點b

Output

對於每組

先輸出一行 "Qi:"表示第i個問題

然後接下來輸出每個問題二叉樹每層的節點,在同一層的節點用空格分開,同一層輸出在一行(每一行末尾沒有空格),不同的層輸出在不同行(入下面Sample Ouput所示)

SampleInput
2

4 5

2 1

3 1

4 2

5 4

1 2

2 1

SampleOutput
Q1:

1

2 3

4

5

Q2:

1

2

#include <bits/stdc++.h>
using namespace std;
struct node
{
	int x;
	int l, r;
	int dept;
	node()
	{
	   l = r = 1;	
	}
};
int main()
{
	int t;
	scanf("%d", &t); 
	for(int k = 1; k <= t; k++)
	{
		int n, m;
		scanf("%d%d", &n, &m);
		
		node s[1100];
		s[1].l = s[1].r = -1;
		s[1].dept = 1;
		int mdept = 1;
		for(int i = 1; i <= n; i++)
		{
			int a, b;
			scanf("%d%d", &a, &b);
			if(s[b].l == -1)
				s[b].l = a;
			else
				s[b].r = a;
			s[a].dept = s[b].dept+1;
			mdept = max(mdept, s[a].dept);
		}
	//	cout<<mdept<<endl;
	    printf("Q%d:\n",k);
		int cnt = 1;
		node tmp = s[1];
		while(cnt <= mdept)
		{
			int flag = 0;
			for(int i = 1; i <= m; i++)
			{
				if(flag && s[i].dept == cnt)
				{
					printf(" %d",i); 
				}
				else if(!flag&&s[i].dept == cnt)
				{
					printf("%d",i);
					flag=1;
				}
			}
			printf("\n");
			cnt++; 
		}
	}
  	return 0;
 
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章