题目: List Leaves
Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.
题目分析:大致意思是输入一棵树,输出为从上到下从左到右输出树中的叶子节点。经过验证题中示例,确实没理解错。
思路:1.建树返回根节点以便索引;
2.层序遍历寻找叶节点并打印;
#include <stdio.h>
typedef int Tree;
#define MaxSize 20
#define Null -1
int M = 0;
struct TreeNode { //数组用来存储二叉树
int data;
Tree left;
Tree right;
}tr[MaxSize];
int BuildTree(struct TreeNode T[])
{
int N, i;
int check[10] = { 0 };
int root;
scanf("%d", &N);
getchar();
if (N)
{
for (i = 0; i < N; i++) {
char l, r;
scanf("%c %c", &l, &r); //读入左右孩子
getchar();
if (l == '-' && r == '-')M++; //叶子节点个数
tr[i].data = i; //节点数据
if (l != '-')
{
tr[i].left = l - '0';
check[tr[i].left] = 1;
}
else tr[i].left = Null;
if (r != '-')
{
tr[i].right = r - '0';
check[tr[i].right] = 1;
}
else tr[i].right = Null;
}
for (i = 0; i < N; i++) //根节点
{
if (check[i] == 0)
break;
}
root = i;
}
return root;
}
void LevelNode(int root)
{
int queue[10] = { 0 }, rear = -1, front = -1; //设置队列,按层次输出
struct TreeNode p;
queue[++rear] = root; //队尾插入根节点
while (front != rear) { //队列不为空
p =tr[queue[++front]]; //队头取出节点
if (p.left != -1)queue[++rear] = p.left; //队尾插入左孩子
if (p.right != -1)queue[++rear] = p.right; //队尾插入右孩子
if (p.left == -1 && p.right == -1) { //输出叶子节点
printf("%d", p.data);
M--;
if (M)printf(" ");
}
}
}
int main()
{
int r = BuildTree(tr);
LevelNode(r);
return 0;
}
这里的队列直接用数组简单粗暴的处理。(不懂,学习)