#include
#include
#define ElemType char
#define MaxQsize 20
#define TRUE 1
#define FALSE 0
using namespace std;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef BiTree QElemType; //设队列元素为二叉树的指针类型
typedef struct
{
QElemType *base;
int front; //头指针,若队列不空,指向队头元素
int rear; //尾指针,若队列不空,指向队尾元素
}SqQueue;
void CreateBiTree_pre(BiTree &T);
void preordertraverse(BiTree T);
void InOrderTraverse(BiTree T);
void postOrderTraverse(BiTree T);
void InitQueue(SqQueue &Q);
bool QueueEmpty(SqQueue Q);
int EnQueue(SqQueue &Q,QElemType &e);
int DeQueue(SqQueue &Q,QElemType &e);
void LevelOrderTraverse(BiTree &T);
void visit(ElemType ch);
int postBiTreeDepth(BiTree T);
int CountNode(BiTree T);
int main()
{
BiTree T;
QElemType e;
int depth,count;
cout<<"请先序输入二叉树的元素,其中'.'表示空树\n";
CreateBiTree_pre(T);
cout<<"先序遍历二叉树为:\n";
preordertraverse(T);cout<
InOrderTraverse(T);cout<
postOrderTraverse(T);cout<
LevelOrderTraverse(T);cout<
depth=postBiTreeDepth(T);
cout<
count=CountNode(T);
cout<
return EXIT_SUCCESS;
}
void CreateBiTree_pre(BiTree &T) //先序建立二叉树
{
char ch;
cin>>ch;
if(ch=='.')
T=NULL;
else
{
if(!(T=(BiTNode*)malloc(sizeof(BiTNode))))
return;
T->data=ch;
CreateBiTree_pre(T->lchild); //构造左子树
CreateBiTree_pre(T->rchild); //构造右子树
}//else
}
void preordertraverse(BiTree T) //先序遍历二叉树
{
if(T)
{
visit(T->data);
preordertraverse(T->lchild);
preordertraverse(T->rchild);
}
}
void InOrderTraverse(BiTree T) //中序遍历二叉树
{
if(T)
{
InOrderTraverse(T->lchild);
visit(T->data);
InOrderTraverse(T->rchild);
}
}
void postOrderTraverse(BiTree T) //后序遍历二叉树
{
if(T)
{
postOrderTraverse(T->lchild);
postOrderTraverse(T->rchild);
visit(T->data);
}
}
void visit(ElemType ch)
{
cout<
void InitQueue(SqQueue &Q) //初始化队列
{
if(!(Q.base=(QElemType*)malloc(MaxQsize*sizeof(QElemType))))
return;
Q.front=Q.rear=0;
cout<<"初始化成功\n";
}
bool QueueEmpty(SqQueue Q) //判空
{
if(Q.front==Q.rear)
return TRUE;
else
return FALSE;
}
int EnQueue(SqQueue &Q,QElemType &e) //入队
{
if((Q.rear+sizeof(QElemType))%(MaxQsize*sizeof(QElemType))==Q.front) //队满
return 0;
else
{
Q.base[Q.rear]=e;
Q.rear=(Q.rear+sizeof(QElemType))%(MaxQsize*sizeof(QElemType));
return 1;
}
}
int DeQueue(SqQueue &Q,QElemType &e) //出队
{
if(QueueEmpty(Q))
return 0;
else
e=Q.base[Q.front];
Q.front=(Q.front+sizeof(QElemType))%(MaxQsize*sizeof(QElemType));
return 1;
}
void LevelOrderTraverse(BiTree &T) //层序遍历二叉树
{
SqQueue Q;
BiTree P;
InitQueue(Q);
if(T)
EnQueue(Q,T);
while(Q.front!=Q.rear)
{
DeQueue(Q,P);
visit(P->data);
if(P->lchild)
EnQueue(Q,P->lchild);
if(P->rchild)
EnQueue(Q,P->rchild);
}//end_while
}
int postBiTreeDepth(BiTree T)
{
int depthval,Leftval=0,Rightval=0;
if(!T)
return 0;
else
{
Leftval=postBiTreeDepth(T->lchild);
Rightval=postBiTreeDepth(T->rchild);
depthval=1+(Leftval>Rightval?Leftval:Rightval);
return depthval;
}//else
}
int CountNode(BiTree T) //统计二叉树的节点个数
{
if(!T)
return 0;
else
return 1+CountNode(T->lchild)+CountNode(T->rchild);
}