原题:
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 Maxsize 1000
#define Nul -1 //当接受到的不是数字而是“-”时,写入-1
using namespace std;
struct Tree{ //数结构
int left;
int right;
};
struct que{ //队列结构
int top;
int number[20];
};
que creat_que(){ //构造队列
que Q;
Q.top = -1;
return Q;
}
que Q=creat_que(); //队列全局变量
Tree ary [10]; //树的全局变量数组
int opt[10],pp=0; //finally output
int top(que Q){
if(Q.top!=-1)
return Q.number[Q.top];
else
return -1;
}
void pop(que *Q){
if(Q->top!=-1)
Q->top--;
else
cout << "Empty";
}
void push(que *Q,int ele){
if(Q->top == -1){
Q->number[0]=ele;
Q->top++;
}
else{
for(int i=Q->top;i>=0;i--){
Q->number[i+1]=Q->number[i];
}
Q->top++;
Q->number[0]=ele;
}
}
int creat_tree(Tree ary[],int n){
int test[n],i;
char ipt1,ipt2;
for(int i=0;i<n;i++)
test[i]=1; //构建一个n项都是1的测试数组
for(int i=0;i<n;i++){
cin >> ipt1 >> ipt2;
if(ipt1!='-'){
ary[i].left=ipt1-'0';
test[ary[i].left]=0; //测试数组是别人“左儿子”或“右儿子”时,其为1,这样保留根是唯一的非零项
}
else
ary[i].left=-1;
if(ipt2!='-'){
ary[i].right=ipt2-'0';
test[ary[i].right]=0;
}
else
ary[i].right=-1;
}
i=0;
while(!test[i]) //找到根下标
i++;
return i; //返回非0的根的下标
}
void input_lvs(int node){
push(&Q,node);
while(Q.top!=-1){
if(ary[top(Q)].left==-1 and ary[top(Q)].right==-1)
opt[pp++]=top(Q);
if(ary[top(Q)].left!=-1){
push(&Q,ary[top(Q)].left);
// cout << "left="<<ary[top(Q)].left<<endl;
}
if(ary[top(Q)].right!=-1){
push(&Q,ary[top(Q)].right);
// cout << "right="<<ary[top(Q)].right<<endl;
}
pop(&Q);
}
}
int main(){
int n,root;
cin >> n;
root=creat_tree(ary,n); //不为空树时创建树结构的数组
input_lvs(root);
for(int i=0;i<pp;i++){
cout << opt[i];
if(i!=pp-1)
cout << " ";
}
return 0;
}