原题目 :https://www.icourse163.org/course/ZJU-93001
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 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
C++ STL库自带的队列用法
#include <queue> 的使用 【参考链接】
#include <iostream>
#include <queue>
using namespace std; //这几个头文件必不可少
int main()
{
queue<int> q; //使用前需定义一个queue变量,且定义时已经初始化
while(!q.empty()) q.pop(); //重复使用时,用这个初始化
q.push(1); //进队列
q.pop(); //出队列
int v=q.front(); //得到队首的值
int s=q.size(); //得到队列里元素个数
return 0;
}
/*转载自
https://www.cnblogs.com/IT-hexiang/p/4084608.html
*/
本人实现代码
#include <iostream>
#include <queue>
#define MaxN 10
using namespace std;
struct TreeNode
{
int Data;
int Left;
int Right;
} TN[MaxN]; // TN[]为全局变量
int buildTree(TreeNode T[], int n);
void LevelorderTraversal(int root);
int main()
{
int N,root;
cin >> N;
root=buildTree(TN, N);
LevelorderTraversal(root);
return 0;
}
int buildTree(TreeNode T[], int n)
{
int i, check[MaxN];
char cl, cr;
if (n == 0) return -2; // 表示为空节点,数值可自设
for (i = 0; i < n; i++)
{
check[i] = -1; //-1表示非子节点。
TN[i].Data = i;
}
for ( i = 0; i < n; i++)
{
cin >> cl >> cr;
if (cl != '-')
{
T[i].Left = cl - '0';
check[T[i].Left] = 1; //1表示对应标号的节点是子节点
}
else T[i].Left = -2;//表示无左边子节点,数值可自设
if (cr != '-')
{
T[i].Right = cr - '0';
check[T[i].Right] = 1; //1表示对应标号的节点是子节点
}
else T[i].Right = -2;//表示无右边子节点,数值可自设
}
for (i = 0; i < n;i++)
if (check[i] == -1) break; //-1表示对应标号的节点是根节点
return i;
}
void LevelorderTraversal(int root)
{
queue<struct TreeNode> Q;
struct TreeNode T;
if (root == -2) return; //当根节点不存在时,直接返回
Q.push(TN[root]);
int flag = 0;
while (!Q.empty())
{
T = Q.front();
Q.pop();
if (T.Left == -2 && T.Right == -2)
{
if (flag == 1) cout << " "; //由于输出结果要求,第一个输出前无空格,随后的节点值需要空格
else flag = 1;
printf("%d", T.Data); //为叶节点
}
if (T.Left!=-2) Q.push(TN[T.Left]); //存在左节点
if (T.Right != -2) Q.push(TN[T.Right]); //存在右节点
}
}
参考博文
【C语言实现】03-树2 List Leaves (过程讲解)
【C++实现】《数据结构》03-树2 List Leaves