7-15 List Leaves (25分)
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>
#include<cstdio>
using namespace std;
struct node{
int num;//编号
int count;//下属节点数目
node *left;
node *right;
} p[11];
int sum(node *p){//统计节点数目
if(p==NULL){
return 0;
}
else{
return 1+sum(p->left)+sum(p->right);
}
}
int level(node *p,int cur){//层数
if(p==NULL){
return cur;
}
else{
return max(level(p->left,cur+1),level(p->right,cur+1));
}
}
int f=0;//作为是否输出空格的标志
void traverse(node *p,int cur,int pos){
if(p==NULL||cur>pos){
return ;
}
else if(cur==pos){
if(p->left==NULL&&p->right==NULL){//叶子节点
if(f) printf(" ");//第一次输出前,不输出空格
printf("%d",p->num);
f=1;//之后输出空格
}
}
else{
traverse(p->left,cur+1,pos);
traverse(p->right,cur+1,pos);
}
}
int main(){
int n;
scanf("%d",&n);
getchar();//换行符
char c;
for(int i=0;i<n;i++){
p[i].num=i;//编号
c=getchar();//第一个字符 ,左子树
if(c=='-'){
p[i].left=NULL;
}
else{
p[i].left=&p[c-'0'];
}
getchar();//空格
c=getchar();//第二个字符,右子树
if(c=='-'){
p[i].right=NULL;
}
else{
p[i].right=&p[c-'0'];
}
getchar();//换行符
}
for(int i=0;i<n;i++){//统计每个节点的下属节点数目
p[i].count=sum(&p[i]);
}
int head=0,max=0;
for(int i=0;i<n;i++){//寻找头结点,存储节点数目多者为头结点
if(p[i].count>max){
max=p[i].count;
head=i;
}
}
int l=level(&p[head],0);
for(int i=0;i<l;i++){
traverse(&p[head],0,i);
}
return 0;
}