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

题目分析:

这道题的题意是按照层序遍历的方法,输出所有的叶节点。那么解这道题分两步,首先,依据给出的信息建树。第二步就是进行层序遍历输出叶节点。建树的话就用数组建就行,然后返回数的根节点。进行层序遍历则借助堆栈,首先将根节点push进去,然后再把左右儿子加到堆栈当中,再依次循环,直到堆栈为空,如果一个节点的左右儿子都为空,说明它是叶节点,就输出。

代码如下:

#include <iostream>
#include <queue>
#define Tree int
#define Max 100
#define Null -1
using namespace std;

struct TreeNode{
	Tree left;
	Tree right;
}T[Max];

int BuildTree(struct TreeNode* T1);   //建树
void PrintListLeaves(struct TreeNode* T1, Tree R);  //输出叶节点

int main()
{
	Tree T2;

	T2 = BuildTree(T);
	if(T2 == -1) {  //当为空树的情况,直接输出0
		cout << 0 << endl;
		return 0;
	} else
		PrintListLeaves(T, T2);

    return 0;
}

int BuildTree(struct TreeNode* T1)
{
	int n, i, Boot = -1;
	char l, r;
	int check[Max] = {0};

	cin >> n;
	getchar();

	if( n ) {
		for( i=0; i<n; i++) {
			scanf("%c %c", &l, &r);
			getchar();
			if( l != '-' ) {
				T[i].left = l - '0';
				check[T[i].left] = 1;
			} else
				T[i].left = Null;
			if( r != '-' ) {
				T[i].right = r - '0';
				check[T[i].right] = 1;
			} else
				T[i].right = Null;
		}

		for( i=0; i<n; i++ ) {
			if( !check[i] )
				break;
		}
		Boot = i;
	}

	return Boot;
}

void PrintListLeaves(struct TreeNode* T1, Tree R)
{
	queue<int> s;     //借助队列,进行层序遍历
	int symbol = 0, j;

	s.push(R);   //把根节点加入队列

	while( !s.empty() ) {
		j = s.front();
		s.pop();

		if( (T1[j].left==Null) && (T1[j].right==Null) ) {    //输出叶节点
			if(symbol == 0)
				symbol = 1;
			else
				cout << " ";
			cout << j;
		}
		if( T1[j].left != Null )    //当左右孩子不为空时,加入队列
			s.push(T1[j].left);
		if( T1[j].right != Null )
			s.push(T1[j].right);
	}
	cout << endl;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值