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 (≤) 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 <stdio.h>
#define Null -1
struct TreeNode
{
char Element;
int Left;
int Right;
}Tree[10];
int ReadTree(struct TreeNode Tree[]);
void ListLeaf(int Root);
int main(){
int Root;
Root = ReadTree(Tree); //读入树
ListLeaf(Root); //输出叶子
return 0;
}
int ReadTree(struct TreeNode Tree[]){
int N,i;
char cl,cr;
scanf("%d",&N);
if(N){
int Flag[10]={0};
for (i = 0; i < N; ++i)
{
scanf("%c %c %c",&Tree[i].Element,&cl,&cr);
if(cl!='-'){
Tree[i].Left = cl - '0';
Flag[Tree[i].Left]=1;
}
else Tree[i].Left = Null;
if(cr!='-'){
Tree[i].Right = cr - '0';
Flag[Tree[i].Right]=1;
}
else Tree[i].Right = Null;
}
for (i = 0; i < N; ++i)
{
if(!Flag[i]) break;/* code */
}
return i;
//判断根节点
}
else
return Null;
}
//需要层序遍历
void ListLeaf(int Root){
int head=0,tail=0,A[10]={0},flag=0;
A[tail++] = Root;
while( head < tail ){ //层序遍历
if(Tree[A[head]].Left != Null)
A[tail++] = Tree[A[head]].Left; //左节点入队
if(Tree[A[head]].Right != Null)
A[tail++] = Tree[A[head]].Right;
if((Tree[A[head]].Left == Null) &&
(Tree[A[head]].Right == Null) ) {
if(flag) printf(" %d",A[head]);
else printf("%d",A[head]);
flag++;
}
head++; //相当于根节点出队
}
}
这个题目差不多是自己独立完成的,开心~
Reflection:
1.利用数组实现一个简单的队列
2.层序遍历
参考资料:https://www.cnblogs.com/8023spz/p/7748203.html