二叉树及其遍历
一遍AC,挺开心的hhh~
简单讲下思路:叶子,顾名思义就是没有左右子树的结点。由于题目要求,叶子结点的输出顺序是从上往下,从左往右。所以用层序遍历法。
当然,这里先找到root树的根。运用队列,将root进队列。然后依次将队头出队,若是叶子则输出,否则且将其有的左右孩子进队,达到层序遍历,就是从上往下,从左往右的要求。
当队列为空,即遍历整个树后,结束。
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>
#include <queue>
using namespace std;
#define OK 1
#define ERROR 0 #define MaxTree 10
#define Null -1 //区别于系统的NULL 0 typedef int Status;/* Status是函数的类型,其值是函数结果状态代码,如OK等 */ typedef struct TreeNode
{
int left;
int right;
} Tree; Tree T[MaxTree]; int BulidTree(Tree T[])
{
int N, check[MaxTree], root = Null; //root = Null 空树则返回Null
char cl, cr; //左右孩子序号
scanf("%d\n",&N);
if(N) {
for(int i = ; i < N; i++)
check[i] = ;
for(int i = ; i < N; i++) {
scanf("%c %c\n",&cl,&cr);
//找root
if(cl != '-') {
T[i].left = cl - '';
check[T[i].left] = ; //不是根节点
}else {
T[i].left = Null;
}
if(cr != '-') {
T[i].right = cr - '';
check[T[i].right] = ; //不是根节点
}else {
T[i].right = Null;
}
} for(int i = ; i < N; i++) //check[]=0的为根节点
if(!check[i]) {
root = i;
break;
}
}
return root;
} void isLeaves(int root)
{
queue<int> queue;
queue.push(root);
int flagSpace = ;
while(!queue.empty()) {
int temp = queue.front();
queue.pop(); //pop()虽然会移除下一个元素,但是并不返回
if( (T[temp].left == Null) && (T[temp].right == Null) ) { //该结点是叶子
if(flagSpace) { //控制输出格式
printf("%d", temp);
flagSpace = ;
}else {
printf(" %d", temp);
}
}else {
if(T[temp].left != Null) //不是叶子把它儿子push进队列
queue.push(T[temp].left);
if(T[temp].right != Null)
queue.push(T[temp].right);
}
}
printf("\n");
}
int main()
{
int root1;
root1 = BulidTree(T);
isLeaves(root1);
return ;
}