5-4 List Leaves (25分)

5-4 List Leaves   (25分)

Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a "-" will be put at the position. Any pair of children are separated by a space.

Output Specification:

For each test case, print in one line all the leaves' indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

Sample Input:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

Sample Output:

4 1 5

http://pta.patest.cn/pta/test/16/exam/4/question/666
#include <cstdio>  
#include <sstream>  
#include <cstring>  
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std ;

#define N 10 

int fa[N] ;

int find(int x )
{
	if(x == fa[x])
		return x;
	return fa[x] = find(fa[x]) ;
}

void merg(int x , int  y)
{
	fa[find(y)] = find(x);
}

struct data{
	int no ;
	int l , r ;
};

data dt[N] ;

typedef struct node
{
	int d;
	struct node *left , *right ;
	node(int _d = 0)
	{
		d = _d ;
		left = NULL ;
		right = NULL ;
	}
}Bnode;

Bnode* createTree(Bnode* root , int d)
{
	root = new node(d);
	if(dt[d].l == -1)
	{
		root->left = NULL ;
	}else{
		root->left = createTree(root->left , dt[d].l) ;
	}
	if(dt[d].r == -1)
	{
		root->right = NULL ;
	}else{
		root->right = createTree(root->right, dt[d].r) ;
	}
	return root ;
}

void bfs(Bnode* root)
{
	queue<Bnode*> que ;
	que.push(root);
	bool flag = true ;
	while(!que.empty())
	{
		Bnode* nn = que.front();
		que.pop();
		if(nn->left == NULL && nn->right == NULL)
		{
			if(flag)
			{
				flag = false ;			
				printf("%d",nn->d);
			}
			else{
				printf(" %d",nn->d);
			}
		}
		if(nn->left != NULL)
		{
			que.push(nn->left);
		}
		if(nn->right!= NULL)
		{
			que.push(nn->right);
		}
	}
}

int main()
{
	//freopen("in.txt","r",stdin) ;
	char l,r ;
	int i ;
	int n ;
	scanf("%d\n" , &n) ;
	for(i = 0 ;i < n;i++)
	{
		fa[i] =  i ;
	}
	for( i = 0 ; i < n ; i++)
	{
		data dtmp ;
		dtmp.no = i ;
		scanf("%c %c\n" ,&l,&r);
		if(l == '-')
		{
			dtmp.l = -1 ;
		}else{
			dtmp.l = l-'0';
			if(find(dtmp.l) != find(i))
				merg(i , dtmp.l );
		}
		if(r == '-')
		{
			dtmp.r = -1 ;
		}else{
			dtmp.r = r - '0';
			if(find(dtmp.r) != find(i))
				merg( i , dtmp.r);
		}
		dt[i] =  dtmp ;
	}
	int rNum =  find(0) ;
	Bnode* root = NULL ;
	root = createTree(root,rNum);
	bfs(root);
	printf("\n");
 	return 0 ;
}


你可能感兴趣的:(5-4 List Leaves (25分))