题目:
输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。 例如输入
8/ \
6 10
/ \ / \
5 7 9 11
输出8 6 10 5 7 9 11。
分析:
这一题就是考的二叉树的层次遍历。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include "TREE.h" //该头文件包含二叉树的建立和先序遍历
int front=0,rear=0;
BTNode * Queue[20];
void Push(BTNode *s)
{
Queue[rear++]=s;
}
void Pop()
{
front++;
}
BTNode *GetTop()
{
return Queue[front];
}
BTNode* Convert(BTNode *L);
int main()
{
BTNode *L=NULL;
CreateTree(&L);
printf("The PreOrder Traversal of nodes in the tree are: \n");
OutputTree(L);
printf("\n");
printf("The LevelOrder Traversal of nodes in the tree are: \n");
L=Convert(L);
printf("\n");
return 0;
}
BTNode *Convert(BTNode *L)
{
BTNode *temp,*cur;
Push(L);
while(front<rear)
{
cur=GetTop();//获取栈中首元素
printf("%c ",cur->num); //输出
if (cur->lChild!=NULL) //若有左节点,压入队列
{
Push(cur->lChild);
}
if (cur->rChild!=NULL) //若有右结点,压入队列
{
Push(cur->rChild);
}
Pop(); //弹出首元素
}
return L;
}
TREE.H头文件:
#ifndef TREE_H
#define TREE_H
#include <stdio.h>
#include <stdlib.h>
typedef struct treeNode
{
struct treeNode *lChild;
struct treeNode *rChild;
char num;
}BTNode;
void CreateTree(BTNode **L);//给出先序遍历,建立二叉树,无孩子结点用#代替。
//具体表述可参考http://acm.njupt.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=1019
void OutputTree(BTNode *L); //先序遍历
void CreateTree(BTNode **L) //注意这里传的是指针的地址!!!
{
char ch;
ch=getchar();
getchar();
if (ch=='#')
{
(*L)=NULL;
}
else
{
*L=(BTNode*)malloc(sizeof(BTNode));
(*L)->num=ch;
CreateTree(&((*L)->lChild));
CreateTree(&((*L)->rChild));
}
}
void OutputTree(BTNode *L)
{
if (L)
{
printf("%c ",L->num);
OutputTree(L->lChild);
OutputTree(L->rChild);
}
}
#endif