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
#include <iostream>
constexpr auto MaxSize = 20;
using namespace std;
using Tree_ = class TreeNode;
using Tree = Tree_*;
class TreeNode {
public:
int Data;
int Left;
int Right;
int Test{ 0 };
};
int CreateTree(Tree T, int N) {
char c1, c2;
for (int i = 0; i < N; i++) {
T[i].Data = i;
cin >> c1 >> c2;
if (c1 == '-') {
T[i].Left = -1;
}
else {
T[i].Left = c1 - '0';
T[T[i].Left].Test = 1;
}
if (c2 == '-') {
T[i].Right = -1;
}
else {
T[i].Right = c2 - '0';
T[T[i].Right].Test = 1;
}
}
for (int i = 0; i < N; i++) {
if (T[i].Test == 0) {
return i;
}
}
}
void Push(int* Queue, int Data, int& tail) {
if (Data == -1) {
return;
}
else {
Queue[++tail] = Data;
}
}
void Pop(int* Queue, Tree T, int& head, int& ret) {
if (T[Queue[head]].Left == -1 && T[Queue[head]].Right == -1) {
if (ret == 0) {
cout << Queue[head];
ret = 1;
}
else {
cout << ' ' << Queue[head];
}
}
Queue[head] = -1;
head++;
}
void PrintTree(Tree T, int root) {
int* Queue = new int[MaxSize];
int head = 0;
int tail = -1;
int ret = 0;
Push(Queue, T[root].Data, tail);
while (head <= tail) {
Push(Queue, T[Queue[head]].Left, tail);
Push(Queue, T[Queue[head]].Right, tail);
Pop(Queue, T, head, ret);
}
delete[] Queue;
}
int main() {
int N, root;
cin >> N;
Tree T = nullptr;
T = new Tree_[N];
root = CreateTree(T, N);
PrintTree(T, root);
return 0;
}