03-树2 List Leaves (25 分)

03-树2 List Leaves (25 分)

大致思路:先找到根结点root(没有任何结点指向它的结点),并且记录叶子的个数,然后运用层序遍历(根据题目要求选的),将叶结点的坐标输出,注意输出格式。

#include<cstdio>
#include<queue>
using namespace std;
const int maxn=20;
struct TNode{
	int left, right;
}T[maxn];
int count=0;
void print(int root){
	if(root==-1)return;
	queue<int> q;
	q.push(root);
	while(!q.empty()){
		root=q.front();
		q.pop();
		if(T[root].left==-1 && T[root].right==-1){
			printf("%d", root);
			count--;
			if(count!=0)printf(" ");
		}
		if(T[root].left!=-1)q.push(T[root].left);
		if(T[root].right!=-1)q.push(T[root].right);
	}
}
int check[maxn];
int main(){
	int n, root=-1;
	char lc, lr;
	scanf("%d\n", &n);
	for(int i=0; i<n; i++)check[i]=0;
	for(int i=0; i<n; i++){
		scanf("%c %c\n", &lc, &lr);
		if(lc=='-'&&lr=='-')count++;
		if(lc!='-'){
			T[i].left=lc-'0';
			check[T[i].left]=1;
		}else{
			T[i].left=-1;
		}
		if(lr!='-'){
			T[i].right=lr-'0';
			check[T[i].right]=1;
		}else{
			T[i].right=-1;
		}
	}
	for(int i=0; i<n; i++){
		if(check[i]==0){
			root=i;
			break;
		}
	}
	print(root);
	return 0;
}