题目
Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.
输入格式
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.
先输入一个小于10的正整数N,代表结点的总数,在接下来的N行每行输入一个结点信息。输入的信息代表了左右儿子结点,当输入’-'时代表无左/右儿子结点,输入的左右儿子结点的信息之间用空格隔开。
输出格式
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.
输出的信息为每个测试用例的叶节点,输出顺序为由上至下,由左至右,在每个结点之间用空格隔开,最后一个结点后面没有多余空格。
输入样例
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
输出样例
4 1 5
这道题算是二叉树中比较基本的题目,主要考察的是二叉树的构建以及对于二叉树的层次遍历。二叉树的层次遍历一般采用的是使用队列来进行遍历。一开始队列中只有一个根节点,当队列的第一个结点出队时,该节点对应的左右儿子结点入队,依次遍历直至整个队列中无结点。当出队的结点为叶结点时,打印出来,最后打印出所有的叶节点。这种遍历方式可以确保题目中提出的从上至下、从左至右打印叶节点的要求。
代码如下:
#define null -1//无左/右儿子结点时序号为null
#include<iostream>
using namespace std;
struct TreeNode//本题采用静态链表的方法构建二叉树,每结点结构有三个信息,分别为结点序号
{
//以及左右儿子结点的序号
int Data;
int Left;
int Right;
}T[10];//用T来存储整个二叉树
struct queue//队列的链式存储
{
TreeNode tree;
queue* next;
};