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
意思就是输出所有子节点就可以了,按照从左到右,从上到下的顺序。用数组存储二叉树,然后用队列bfs层序遍历即可,找到左右节点都为空即可输出,比较简单。
#include<iostream>
#include<queue>
using namespace std;
struct node
{
int key,left,right;
}a[11];
int check[11];
void judge(int x)
{
queue<node>q;
q.push(a[x]);
while(!q.empty())
{
node temp=q.front();
q.pop();
if(temp.left==-1&&temp.right==-1&&!q.empty())
{
cout<<temp.key<<" ";
}
else if(temp.left==-1&&temp.right==-1&&q.empty())
{
cout<<temp.key<<endl;
}
else
{
if(temp.left!=-1)
{
q.push(a[temp.left]);
}
if(temp.right!=-1)
{
q.push(a[temp.right]);
}
}
}
}
int main()
{
int root;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
a[i].key=i;
char l,r;
cin>>l>>r;
if(l!='-')
{
a[i].left=l-'0';
check[l-'0']=1;
}
else
{
a[i].left=-1;
}
if(r!='-')
{
a[i].right=r-'0';
check[r-'0']=1;
}
else
{
a[i].right=-1;
}
}
for(int i=0;i<n;i++)
{
if(!check[i])
{
root=i;
a[root].key=i;
break;
}
}
judge(root);
return 0;
}