欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

List Leaves (25 分)

程序员文章站 2022-05-17 21:24:12
...

 

 

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