题目:
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
作者: 陈越
单位: 浙江大学
时间限制: 400 ms
内存限制: 64 MB
解题思路:
层序遍历:创建队列保存元素,先推入根节点,判断其是否为叶子节点,是则输出,否则推入其儿子,
最后抛出该节点,这样就完成了一次循环,到抛出最后一个结点的时候队列为空,则循环结束。
#include <iostream>
#include <deque>
using namespace std;
//用结构数组表示二叉树
struct StreeNode
{
int left;
int right;
}T1[10];
int biuldTree(struct StreeNode T[]);
void inoderTraversal(int );
void levelTraversal(int);
int main()
{
int R1 = 0;
R1 = biuldTree(T1);//建造二叉树
//inoderTraversal(R1);//中序遍历
levelTraversal(R1);//层序遍历
system("pause");
return 0;
}
void inoderTraversal(int r1)
{
int flag = 0;
if (r1 == -1)return;
inoderTraversal(T1[r1].left);
if (T1[r1].left == -1 && T1[r1].right == -1){ flag ? cout << r1 << " " : cout << r1; flag++; }
inoderTraversal(T1[r1].right);
}
void levelTraversal(int r1)
{
if (r1==-1)
return;
int flag = 0;
deque<int>d;//建立双端队列
d.push_back(r1);//将根节点添加入队列
while (!d.empty())
{
if (T1[d[0]].left == -1 && T1[d[0]].right == -1)//如果膝下无子女则为叶子节点输出
{
flag ? cout << " " << d[0] : cout << d[0]; flag++;
}
if (T1[d[0]].left != -1)d.push_back(T1[d[0]].left);//有儿子的话把儿子的编号推入队列
if (T1[d[0]].right != -1)d.push_back(T1[d[0]].right);
d.pop_front();//抛出首元素
}
}
int biuldTree(struct StreeNode T[])
{
int N, Root = -1;//当N为0即输入空树的时候,根节点的编号root应该为-1
char cl, cr;
int check[10];//识别根节点用的数组
cin >> N;
if (N)
{
for (int &i : check) i = 0; //全部元素初始化为0
for (int i = 0; i < N; i++)
{
cin >> cl >> cr;
if (cl != '-')//左边有儿子
{
T[i].left = cl - '0';//left是int,cl是char,char-char==int(ascll码值的差);
check[T[i].left] = 1; //当你是别人的儿子的时候,你的check变为1
}
else T[i].left = -1;//左边没儿子,就把左儿子设为-1`在这里插入代码片`
if (cr != '-')
{
T[i].right = cr - '0';
check[T[i].right] = 1;
}
else T[i].right = -1;
}
}
else return -1;//与根节点初始化为-1的目的一样,当输入空树的时候保证根节点编号为-1,两者写其中一个就行。
for (int i = 0; i < N; i++)//是别的儿子的check都是1.还是0的那个就是根节点
{
if (!check[i])
{
Root = i;
break;
}
}
return Root;//返回根节点编号
}