//二叉树的层次遍历和其深度
#include <cstdio>
#include <cstdlib>
//define _OJ_
#define maxsize 100
typedef struct tree1
{
char data;
struct tree1 *lchild;
struct tree1 *rchild;
} tree1, *tree;
typedef struct queue1
{
tree data;
struct queue1 *next;
} queue1, *queue;
typedef struct Linkqueue1
{
queue front;
queue rear;
}Linkqueue1, *Linkqueue;
Linkqueue
init_queue(void)
{
Linkqueue q;
q = (Linkqueue) malloc (sizeof(Linkqueue1));
q->front = q->rear = (queue) malloc (sizeof(queue1));
q->front->next = NULL;
return q;
}
void
Enqueue(Linkqueue q, tree T)
//将新的节点插入队尾
{
queue p;
p = (queue) malloc (sizeof(queue1));
p->data = T; p->next = NULL;
q->rear->next = p;
q->rear = p;
}
tree
Dequeue(Linkqueue q)
//从队头删除节点
{
queue p;
p = q->front->next;
q->front->next = p->next;
if(q->rear == p) q->rear = q->front;
return p->data;
}
tree
creat_tree(tree T)
{
char ch;
scanf("%c", &ch);
if(ch == ‘#‘)
T = NULL;
else
{
T = (tree) malloc (sizeof(tree1));
T->data = ch;
T->lchild = creat_tree(T->lchild);
T->rchild = creat_tree(T->rchild);
}
return T;
}
int
isempty(Linkqueue q)
{
if(q->front == q->rear)
return 1;
else
return 0;
}
void
travertree(tree T)
{
Linkqueue q;
tree T2;
q = init_queue();
Enqueue(q,T);
while ( !isempty(q)) {
T2 = Dequeue(q);
printf("%c\n", T2->data);
if(T2->lchild != NULL)
Enqueue(q,T2->lchild);
if(T2->rchild != NULL)
Enqueue(q,T2->rchild);
}
}
int
deep(tree T)
{
int dept = 0;
if(T)
{
int lchild_deep, rchild_deep;
lchild_deep = deep(T->lchild);
rchild_deep = deep(T->rchild);
dept = lchild_deep >= rchild_deep ? (lchild_deep + 1) : (rchild_deep + 1);
}
return dept;
}
int main(int argc, char const *argv[]) {
#ifndef _OJ_ //ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
tree T;
T = creat_tree(T);
printf("deep == %d\n", deep(T));
travertree(T);
return 0;
}
/*deep == 3
A
B
C
D*/