您的位置:首页 > 其它

【题目20】层序遍历一个棵二叉树

2009-09-19 15:34 423 查看
题目:怎样从顶部开始逐层打印二叉树结点数据?请编程。

分析:可以利用队列的先进先出的特性,逐次打印队列中的节点。

45

21 65

10 24 50 70

层序遍历的结果: 45,21,65,10,24,50,70

首先45入队,这时队列中有节点元素了,就取出一个来打印,并将

该节点的左子树和右子树分别入队(如果子树不为空的情况下),然后

取下一个先入队的元素打印,并将其左子树和右子树节点入队,一直这

样操作,直到队列为空,打印结束。

源代码:

#include <stdio.h>
#include <stdlib.h>

#define QSIZE 100
typedef struct BTree

{
int value;
struct BTree* lChild;
struct BTree* rChild;
} BTree;
//using the feature of the queue,first in first out
struct MyQueue

{
BTree* queue[QSIZE];
int front;
int rear;

} myQueue;

void InitQueue()

{
myQueue.rear = QSIZE - 1;
myQueue.front = myQueue.rear;
for(int i = 0;i < QSIZE;i++)
myQueue.queue[i] = NULL;
}

int EnQueue(BTree* newNode)

{
if(myQueue.front >= 1)
myQueue.queue[myQueue.front--] = newNode;
else
return 0;
return 1;
}

BTree* DeQueue()
{
int t;
if(myQueue.front != myQueue.rear){
t = myQueue.rear;
myQueue.rear--;
return myQueue.queue[t];
}
else
return NULL;

}

void  LevelTraversal(BTree** root)
{
InitQueue();
BTree* lc = (BTree* ) malloc(sizeof(BTree));
BTree* rc = (BTree* ) malloc(sizeof(BTree));
BTree* p = (BTree* ) malloc(sizeof(BTree));
if((!lc) || (!rc) || (!p)){
printf("Out of memery/n");
exit(-1);
}
p = *root;
if(!p) {
printf("Empty Tree,build it first!/n");
}
EnQueue(p); // enqueue the root of the tree

while (myQueue.front != myQueue.rear){
p = DeQueue();
printf("%d ",p->value);
lc = p->lChild;
rc = p->rChild;
if(lc != NULL)
EnQueue(lc);
if(rc != NULL)
EnQueue(rc);
}
printf("/n");
}

//recursively insert a tree node
BTree* Insert(BTree* T, int value)
{
if(T == NULL)
{
T = (BTree*)malloc(sizeof(struct BTree));
if( T == NULL)
printf("Malloc Failed.");
else
{
T->value  = value;
T->lChild = T->rChild = NULL;
}
}
else if(value < T->value)
T->lChild = Insert(T->lChild,value);
else if(value > T->value)
T->rChild = Insert(T->rChild, value);
return T;
}

BTree* MakeEmpty(BTree* T)
{
if(T != NULL)
{
MakeEmpty(T->lChild);
MakeEmpty(T->rChild);
free(T);
}
return NULL;
}

int main()
{
BTree* T = NULL;
T = Insert(T,45);
T = Insert(T,21);
T = Insert(T,65);
T = Insert(T,10);
T = Insert(T,50);
T = Insert(T,70);
T = Insert(T,24);
LevelTraversal(&T);
MakeEmpty(T);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: