03-树1. List Leaves 经验

本文详细解释了如何构建二叉树并利用队列实现层序遍历,重点在于从节点0到节点N-1的左右孩子构建过程及层序遍历输出所有叶子节点的索引。

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 N-1. 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


1.我觉得这个题的难点还是在对题意的理解给出从节点0到节点N-1的各个左右孩子,画出二叉树图如下:






2.二叉树构建好后用队列直接层序遍历就好。


#include<stdio.h>
typedef struct bintree{
	int data,Ileft,Iright;
}Bintree;

void InOutQueue(int* p,Bintree* tree,int* star,int* end);
int input(void);

int main(){
//	定义及初始化 
	int n,i;
	scanf("%d",&n);
	Bintree BinTree[n];
	int chack[n],boot;
	int queue[n+1],star = -1,end = 0;
	queue[0] = -1;
	queue[n] = -1;
	for(i = 0;i<n;i++)
		chack[i] = 0;
//	给节点的左右孩子赋值,若为'-'则赋值为-1 
	for(i = 0;i<n;i++){
		BinTree[i].data = i; 
		BinTree[i].Ileft = input();
		if(BinTree[i].Ileft != -1)
			chack[BinTree[i].Ileft] = 1;
		BinTree[i].Iright = input();
		if(BinTree[i].Iright != -1)
			chack[BinTree[i].Iright] = 1;
	}
//	查找根节点 
	for(i = 0;i<n;i++)
		if(!chack[i])
			boot = i;
//	根节点入队 
	queue[end] = boot;
	end++;
//	进行一系列入队出队操作 
	while(1!= end -star){
		InOutQueue(queue,BinTree,&star,&end);
	}
	
	return 0;
}

void InOutQueue(int* p,Bintree* tree,int* star,int* end){
	int t = p[(*star)+1];
	static int P = 0;
	if(tree[t].Ileft!=-1){
		p[*end] = tree[t].Ileft;
		(*end)++;
	}
	if(tree[t].Iright!=-1){
		p[*end] = tree[t].Iright;
		(*end)++;
	}
	if(tree[t].Ileft == -1 && tree[t].Iright == -1){
		if(!P){
			printf("%d",t);
			P = 1;
		}else
			printf(" %d",t);
	}
	(*star)++;
}

int input(void){
	char c;
	do{
		c = getchar();
	}while(c != '-' && (c<'0' || c>'9'));
	if(c == '-')
		return -1;
	else
		return c-'0';	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值