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
采用的结构体数组的形式来储存树。
结构体声明如下:
struct TreeNode {
int Left;
int Right;
int Root=Null;
}Tree[11];
结构体中的根是为了方便最后确定树的根,这一信息需要全部数据读完才可以知道。
整个树的根的Root=Null,由此可以找到root;
题目要找的是叶节点,左右子树全为Null即为叶节点的判断条件。依据题意该题采用队列实现的层次遍历。
AC代码:
#include<iostream>
#include<queue>
using namespace std;
const int Null = -1;
int flag = 0;
struct TreeNode {
int Left;
int Right;
int Root=Null;
}Tree[11];
void LevelOrder(int BT)
{
queue<int> Q;
if (BT == Null) return;
Q.push(BT);
while (!Q.empty())
{
int t = Q.front();
Q.pop();
if ((Tree[t].Right == Null) && (Tree[t].Left == Null))
{
if (flag) cout << " ";
flag++;
cout << t;
}
if (Tree[t].Left != Null) Q.push(Tree[t].Left);
if (Tree[t].Right != Null) Q.push(Tree[t].Right);
}
}
int main()
{
int n, root;
char c1, c2;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> c1 >> c2;
if (c1 == '-') Tree[i].Left = Null;
else
{
Tree[i].Left = c1 - '0';
Tree[Tree[i].Left].Root = i;
}
if (c2 == '-') Tree[i].Right = Null;
else
{
Tree[i].Right = c2 - '0';
Tree[Tree[i].Right].Root = i;
}
}
for (int i = 0; i < n; i++)
if (Tree[i].Root == Null) root = i;
LevelOrder(root);
return 0;
}