【每日刷题】 PAT 数据结构 03-树2 List Leaves (25 分)

题目描述:
在这里插入图片描述
在这里插入图片描述
代码如下:

//03-树2 List Leaves (25 分)
#include <stdio.h>

typedef struct TreeNode{
	int index;
	int Left;
	int Right;
}TNode;

TNode T[10];

typedef struct queue{
	TNode data[10];
	int rear;
	int front;
}Queue;

Queue q;
int CreatTree( TNode T[] );           //创建一棵树
void print_leave( int r );            //打印叶结点
void InitQueue( Queue &q );           //创队
void EnQueue( TNode T, Queue &q );    //入队
void DeQueue( TNode &T, Queue &q );   //出队
 
int count = 0;

int main()
{
	int r;
	r = CreatTree( T );
	print_leave( r );
	return 0;
}

int CreatTree( TNode T[] )
{
	int n, i;
	scanf( "%d", &n );
	int root = -1;
	int check[n];
	for( i = 0; i < n; i++ )
		check[i] = 0;
	for( i = 0; i < n; i++ ){
		char cl, cr;
		scanf( "\n%c %c", &cl, &cr );
		if( cl == '-' )
			T[i].Left = -1;
		else{
			T[i].Left = cl - '0';
			check[ T[i].Left ] = 1;
		}
		if( cr == '-' )
			T[i].Right = -1;
		else{
			T[i].Right = cr - '0';
			check[ T[i].Right ] = 1;
		}
		if( cl == '-' && cr == '-' )
			count++;
		T[i].index = i;
	}
	for( i = 0; i < n; i++ )
		if( check[i] == 0 ){
			root = i;
			break;
		}
	return root;
} 

int IsLeave( int r )
{
	if( T[r].Left == -1 && T[r].Right == -1 )
		if( count == 1 )
		 	printf( "%d", r );
		else{
			count--;
			printf( "%d ", r );
		}
}
void print_leave( int r )
{
	InitQueue( q );
	TNode p;
	EnQueue( T[r], q );
	while( q.rear != q.front ){
		DeQueue( p, q );
		if( p.Left == -1 && p.Right == -1 )
			if( count == 1 )
				printf( "%d", p.index );
			else{
				count--;
				printf( "%d ", p.index );
			}
		if( p.Left != -1 )
			EnQueue( T[p.Left], q );
		if( p.Right != -1 )
			EnQueue( T[p.Right], q );
	}
}

void InitQueue( Queue &q )
{
	q.rear = q.front = 0;
}

void EnQueue( TNode T, Queue &q )
{
	q.data[ q.rear++ ] = T;
}

void DeQueue( TNode &T, Queue &q )
{
	T = q.data[ q.front++ ];
}

猜你喜欢

转载自blog.csdn.net/qq_40344308/article/details/89284496
今日推荐