C语言写树的遍历
//对树进行底层遍历时使用了队列的结构
基础类型:
typedef enum {FALSE = 0,TRUE = 1} Bool;
typedef enum {VOERFLOW = -2,UNDERFLOW = -1, ERROR = 0,OK = 1} Status;
树的二叉链表结点定义:
typedef struct Node{
char data;
struct Node *firstchild,*nextbrother;
}Node,*TreeNode;
//实现队列基本操作的函数原型表
void InitQueue(Queue *Q); //初始化队列
Bool IsEmpty(Queue Q); //判断队列是否为空,若是则返回TRUE,否则返回FALSE
void EnQueue(Queue *Q,TreeNode p); //元素入队列
void DeQueue(Queue *Q,TreeNode *p); //元素出队列
//函数代码
Status LevelTraverser(TreeNode root)
{
/*层序遍历树,树采用孩子-兄弟表示法,root是树根结点的指针*/
Queue tmpQ;
TreeNode ptr,brotherptr;
if( !root )
return ERROR;
InitQueue(&tmpQ);
EnQueue(tmpQ,root);
brotherptr = root->nextbrother;
while(brotherptr)
{
EnQueue(&tmpQ,brotherptr);
brotherptr=brotherptr->nextbrother;
}
while(!IsEmpty(tmpQ))
{
DeQueue(&tmpQ,&ptr);
printf("%c\t",ptr->data);
if(!ptr->firstchild) continue;
EnQueue(&tmpQ,ptr->firstchild);
brotherptr =ptr->brotherptr->nextbrother;
while(brotherptr)
{
EnQueue(&tmpQ,brotherptr);
brotherptr = brotherptr->nextbrother;
}
}
return OK;
}