List Leaves 树的层序遍历
3-树2 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
思路: 首先确定程序框架: 主体程序:建立一个二叉树————二叉树的遍历 ———— 输出叶节点
建立二叉树的过程,先定义一个struct 结构。scanf 获得左子树和右子树。
二叉树的遍历是通过构造一个队列,如果是叶节点,则没有左子树和右子树,则输出该节点。
同时注意格式:中间用空格隔开,因此使用一个int leaves记录叶节点的个数,第一个叶节点不输出空格。
#include<cstdio> #include<algorithm> #include<queue> using namespace std; #define Tree int #define Null -1 queue<Tree> q; struct TreeNode{ int data; Tree left; Tree right; }T[12]; Tree BuildTree(struct TreeNode T[]){ //建树过程 int n,i; scanf("%d",&n); getchar(); //接收空格 int check[n]={0}; char cl,cr; if(!n)return Null; if(n){ for(i=0;i<n;i++){ scanf("%c %c",&cl,&cr); T[i].data=i; getchar(); if(cl!='-'){ T[i].left=cl-'0'; check[T[i].left]=1; }else T[i].left=Null; if(cr!='-'){ T[i].right=cr-'0'; check[T[i].right]=1; }else T[i].right=Null; } } for(i=0;i<n;i++){ if(!check[i])return i; } } void ListTraverse(Tree root){ //树的层序遍历,通过队列实现 int leaves=0; //用于记录叶节点 q.push(root); while(!q.empty()){ Tree node=q.front(); q.pop(); if(T[node].left==Null&&T[node].right==Null){ if(leaves++)printf(" "); //第一个叶节点前面不加空格 printf("%d",T[node].data); } if(T[node].left!=Null)q.push(T[node].left); if(T[node].right!=Null)q.push(T[node].right); } } int main(){ Tree root=BuildTree(T); ListTraverse(root); return 0; }