#include<iostream>
using namespace std;
typedef int elemtype;
#define Maxsize 50
typedef struct BiTNode {
elemtype data;
struct BiTNode *lchild,*rchild;
} BiTNode,*BiTree;
typedef struct Queue { //构造树节点队列
BiTree tree[Maxsize];
int front=0,rear=0;
} Queue;
bool QueueEmpty(Queue q) {//判断队空
if(q.rear==q.front)
return true;
else
return false;
}
bool QueueFull(Queue q) { //判断队满
if((q.rear+1)%Maxsize==q.front)
return true;
else
return false;
}
bool InQueue(Queue &q,BiTree b) { //入队
if(QueueFull(q))
return false;
q.tree[q.rear]=b;
q.rear=(q.rear+1)%Maxsize;
return true;
}
bool OutQueue(Queue &q,BiTree &b) { //出队
if(QueueEmpty(q))
return false;
b=q.tree[q.front];
q.front=(q.front+1)%Maxsize;
return true;
}
void InitBiTree(BiTree &b) {//构造二叉树
b=(BiTree)malloc(sizeof(BiTNode));
b->lchild=NULL;
b->rchild=NULL;
}
void Insertlchild(BiTree &b,BiTree s) { //插入左子树
if(b!=NULL)
b->lchild=s;
}
void Insertrchild(BiTree &b,BiTree s) { //插入右子树
if(b!=NULL)
b->rchild=s;
}
void visit(BiTree b) {
cout << b->data << endl;
}
void PreOrder(BiTree b) {//先序遍历
if(b!=NULL) {
visit(b);
PreOrder(b->lchild);
PreOrder(b->rchild);
}
}
void InOrder(BiTree b) {//中序遍历
if(b!=NULL) {
InOrder(b->lchild);
visit(b);
InOrder(b->rchild);
}
}
void PostOrder(BiTree b) {//后序遍历
if(b!=NULL) {
PostOrder(b->lchild);
PostOrder(b->rchild);
visit(b);
}
}
void LayerOrder(BiTree b) { //层次遍历
Queue q;
InQueue(q,b);
BiTree s;
while(!QueueEmpty(q)) {
OutQueue(q,s);
visit(s);
if(s->lchild!=NULL)
InQueue(q,s->lchild);
if(s->rchild!=NULL)
InQueue(q,s->rchild);
}
}
int treeDepth(BiTree b) {//求树的深度
if(b==NULL)
return 0;
int l=treeDepth(b->lchild);
int r=treeDepth(b->rchild);
return l>r?l+1:r+1;
}
int main()
{
BiTree root;
InitBiTree(root);
root->data=1;
for(int j=2; j<4; j++) {
BiTree s;
InitBiTree(s);
s->data=j;
if(j%2==0)
Insertlchild(root,s);
else
Insertrchild(root,s);
}
cout << "先序" << endl;
PreOrder(root);
cout << "中序" << endl;
InOrder(root);
cout << "后序" << endl;
PostOrder(root);
cout << "层次" << endl;
LayerOrder(root);
cout << "树深" << endl;
cout << treeDepth(root) << endl;
return 0;
}