03-树2 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 NN (\le 10≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N-1N−1. Then NN 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
- 时间限制:400ms
- 内存限制:64MB
- 代码长度限制:16kB
- 判题程序:系统默认
- 作者:陈越
- 单位:浙江大学
题目判定
解题程序
题意:已知n(n《 10 )表示二叉树的节点数,随后输入:n个节点的左右儿子节点;为空时,即没有左或右儿子就输入‘-’;然后让你从上到下,从左到右的顺序输出各叶子节点;
分析: 查找头结点;层序遍历。
根据头结点没有父亲结点,先找到头结点;
再按层序遍历的思想。从头结点开始,依次把每个结点放入队列中,然后依次对队列头判断是不是叶子结点(即没有左右儿子);
#include <stdio.h>
#include <stdlib.h>
#include <queue>
#define MAXN 11
using namespace std;
typedef struct { /// 定义树的结构
int index;
int lchild;
int rchild;
} Node;
Node node[MAXN];
int isRoot[MAXN] = { 0 }; ///为找出根节点,初始化为0;当该结点为儿子结点时变为1;最终有一个为0的即为根结点;
int main()
{
int n, i;
scanf( "%d", &n );
char ch = getchar();
for( i = 0; i < n; i++ )
{
char left, right;
scanf( "%c %c", &left, &right );
char ch = getchar();
node[i].index = i;
if( left != '-' )
{
node[i].lchild = left - '0';
}
else
{
node[i].lchild = -1;
}
if( right != '-' )
{
node[i].rchild = right - '0';
}
else
{
node[i].rchild = -1;
}
}
// 查找根结点
for( i = 0; i < n; i++ )
{
int child;
if( node[i].lchild != -1 )
{
child = node[i].lchild;
isRoot[child] = 1;
}
if( node[i].rchild != -1 )
{
child = node[i].rchild;
isRoot[child] = 1;
}
}
int root = 0;
for( i = 0; i < n; i++ )
{
if( isRoot[i] == 0 )
{
root = i;
break;
}
}
//printf( "root: %d\n", root );
// 层序遍历二叉树
queue<Node> q;
q.push( node[root] );
int flag = 0;
while( !q.empty() )
{
Node curNode = q.front();
q.pop();
if( curNode.lchild != -1 )
{
int child = curNode.lchild;
q.push( node[child] );
}
if( curNode.rchild != -1 )
{
int child = curNode.rchild;
q.push( node[child] );
}
if( curNode.lchild == -1 && curNode.rchild == -1 )
{
if( flag == 0 )
{
printf( "%d", curNode.index );
flag = 1;
}
else
{
printf( " %d", curNode.index );
}
}
}
printf("\n");
return 0;
}