层次遍历,依次输出树的叶子结点
https://pintia.cn/problem-sets/1077214780527620096/problems/1106167947099181057
List Leaves
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.1
2
3
4
5
6
7
8
9
10Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
1 | Sample Output: |
层次遍历,依次输出树的叶子结点
用队列实现层次遍历,注意队列的指针的使用
注释详见代码
代码
1 |
|