2020-12-12
题目来源:https://pintia.cn/problem-sets/1302953266564911104/problems/1310235296110600193
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
题意:按从左到右、从上到下的顺序输出叶子节点
思路:由于数据都是小于10的整数,所以可以用数组存储二叉树;层次遍历二叉树则需要一个队列存储每一层的节点。遇到叶子节点就输出。
数组存储二叉树+层次遍历
#include <iostream>
using namespace std;
#define Maxsize 10 //树结点最大数目为10
#define Tree int
#define Null -1
struct TreeNode {
int element;
Tree left;
Tree right;
}T[Maxsize];
int BuildTree(struct TreeNode T[]); //创建一棵树
void LevelOrderTraversal(int root); //层次遍历
int num=0; //全局变量,叶子结点个数
int BuildTree(struct TreeNode T[]) {
int N,root=Null;
scanf_s("%d", &N);
char l1, r1;
if (N) {
root = root + 1;
for (int i = 0; i < N; i++) {
root = root + i;
T[i].element = i;
getchar(); //读入换行符
scanf_s("%c", &l1);
scanf_s(" %c", &r1);
if ((l1 == '-') && (r1 == '-')) { num++; } //叶子结点个数
if (l1 == '-') {
T[i].left = Null;
}
else {
T[i].left = l1 - '0';
root = root - T[i].left; //查找根结点
}
if (r1 == '-') {
T[i].right = Null;
}
else {
T[i].right = r1 - '0';
root = root - T[i].right;
}
}
}
return root;
}
void LevelOrderTraversal(int root) {
int queue[10] = { 0 }; //设置队列,按层次输出
int rear = -1, front = -1;
queue[++rear] = root; //队尾插入根结点
struct TreeNode p;
while (rear!=front) { //队列不为空
p = T[queue[++front]]; //队头取出节点
if (p.left != Null) { queue[++rear] = p.left; } //队尾插入左孩子
if (p.right != Null) { queue[++rear] = p.right; } //队尾插入右孩子
if ((p.left == Null) && (p.right == Null)) {
num--;
printf("%d", p.element); //输出叶子结点
if (num) { printf(" "); }
}
}
}
int main()
{
int root;
root=BuildTree(T); //建树
LevelOrderTraversal(root); //层次遍历+输出叶子结点
system("pause");
return 0;
}