树2 List Leaves (C++)
#题目
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++代码
#include<iostream>
#define Null -1
#define QUEUEMAXSIZE 10 //队列大小
using namespace std;
typedef struct Node Tree;
struct Node //树节点
{
int Rchild;
int Lchild;
};
Tree* tree;
typedef struct Queue Queue;
struct Queue //队列
{
int* p;
int front;
int rear;
int maxsize;
};
Queue* creatQueue(int maxsize) //创建循环队列
{
Queue* queue = new Queue;
queue->front = 0;
queue->rear = 0;
queue->maxsize = maxsize;
queue->p = new int[maxsize];
return queue;
}
void addQueue(Queue* Q,int num) //向队列加入
{
if ((Q->rear + 1) % Q->maxsize == Q->front) //队列满
return;
Q->rear = (Q->rear + 1) % Q->maxsize;
Q->p[Q->rear] = num;
}
bool IsEmpty(Queue* Q) //返回队列是否为空
{
if (Q->front == Q->rear) //队列空
return true;
else return false;
}
int Delete(Queue* Q) //删除队尾
{
if (!IsEmpty(Q))
{
Q->front = (Q->front + 1) % Q->maxsize;
return Q->p[Q->front];
}
else return Null;
}
int c[20] = { 0 };//创建并初始化输出列表,即叶子结点的编号
int size1 = 0; //记录叶子结点的数量
void traverse(Tree* tree,int Root)
{
Queue* Q = creatQueue(QUEUEMAXSIZE);
addQueue(Q, Root);
while (!IsEmpty(Q))
{
int temp = Delete(Q);
if (temp != Null)
{
if (tree[temp].Lchild != Null)
{
addQueue(Q, tree[temp].Lchild);
}
if (tree[temp].Rchild != Null)
{
addQueue(Q, tree[temp].Rchild);
}
if (tree[temp].Lchild == Null && tree[temp].Rchild==Null) //如果没有子节点,则将其编号存入输出数组
{
c[size1] = temp;
size1++;
}
}
}
}
int main()
{
int n; //树的大小
cin >> n;
tree = new Tree[n];
int* p;
if (n > 0)//防止树为空
{
string temp;
p = new int[n] {0}; //初始化记录数组,负责记录子节点的编号,除去所有的子节点,剩下的一个就是树的根节点
for (int i = 0; i < n; i++)
{
cin >> temp;
if (temp == "-")
tree[i].Lchild = Null;
else
{
tree[i].Lchild = atoi(temp.c_str());
p[tree[i].Lchild]++;
}
cin >> temp;
if (temp == "-")
tree[i].Rchild = Null;
else
{
tree[i].Rchild = atoi(temp.c_str()); //将string类转化为int类型
p[tree[i].Rchild]++;
}
}
}
else return 0;
int Root = 0;
for (int i = 0; i < n; i++)
{
if (!p[i])
{
Root = i;
break;
}
}
traverse(tree,Root); //层序遍历整个树,如果为叶子结点就存起来
for (int i = 0; i < size1; i++)
{
cout << c[i];
if (i != size1 - 1) //最后一个空格不输出
cout << " ";
}
system("pause");
return 0;
}