树2 List Leaves

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 () 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

#include <stdio.h>

#define Null -1

struct TreeNode
{
	char Element;
	int Left;
	int Right;
}Tree[10];

int ReadTree(struct TreeNode Tree[]);
void ListLeaf(int Root);

int main(){
	int Root;
	Root = ReadTree(Tree);  //读入树
	ListLeaf(Root); //输出叶子
	
	return 0;
}

int ReadTree(struct TreeNode Tree[]){
	int N,i;
	char cl,cr;
	scanf("%d",&N);
	if(N){
		int Flag[10]={0};
		for (i = 0; i < N; ++i)
		{
			scanf("%c %c %c",&Tree[i].Element,&cl,&cr);
			if(cl!='-'){
				Tree[i].Left = cl - '0';
				Flag[Tree[i].Left]=1;
			}
			else Tree[i].Left = Null;
			if(cr!='-'){
				Tree[i].Right = cr - '0';
				Flag[Tree[i].Right]=1;
			}
			else Tree[i].Right = Null;			
		}
		for (i = 0; i < N; ++i)
		{
			if(!Flag[i]) break;/* code */
		}
		return i;
	   //判断根节点

	}
	else
		return Null;
}

//需要层序遍历
void ListLeaf(int Root){
	int head=0,tail=0,A[10]={0},flag=0;
	A[tail++] = Root;
	while( head < tail ){                            //层序遍历
		if(Tree[A[head]].Left != Null) 
			A[tail++] =  Tree[A[head]].Left;  //左节点入队
		if(Tree[A[head]].Right != Null) 
			A[tail++] =  Tree[A[head]].Right;
		
		if((Tree[A[head]].Left == Null) &&
			(Tree[A[head]].Right == Null) ) {
			if(flag) printf(" %d",A[head]);
			else printf("%d",A[head]);
			flag++;
		}
		head++;                      //相当于根节点出队
	}

}

这个题目差不多是自己独立完成的,开心~

Reflection:

    1.利用数组实现一个简单的队列

    2.层序遍历

参考资料:https://www.cnblogs.com/8023spz/p/7748203.html

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值