按先序次序输入二叉树中结点的值,建立一棵以二叉链表作存储结构的二叉树,然后按先序、中序、后序、层序分别遍历这棵二叉树,并完成二叉树的相应信息的统计(如各种结点数目、计算高度等)
头文件:1.h
#include <iostream>
#include <malloc.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define OK 1
typedef int Status;
using namespace std;
头文件:2.h
#define MAXQSIZE 100
typedef char TElemType;
typedef struct BiTNode
{
TElemType data;
BiTNode *lchild, *rchild;
}BiTNode,*BiTree;
typedef BiTree QElemtype;
typedef struct
{
QElemtype *base;
int front;
int rear;
}SqQueue;
头文件:3.h(函数的具体实现)
Status CreatBitree(BiTree &T)//先序建立二叉树
{
TElemType ch;
cin >> ch;
if (ch == '#')
{
T = NULL;
}
else
{
T = (BiTNode *)malloc(sizeof(BiTNode));
if (!T)
return OVERFLOW;
T->data = ch;
CreatBitree(T->lchild);
CreatBitree(T->rchild);
}
return OK;
}
void inOder(BiTree T)//中序遍历
{
if (T)
{
inOder(T->lchild);
cout << ' ' << T->data;
inOder(T->rchild);
}
}
void PreOder(BiTree T)//先序遍历
{
if (T)
{
cout <<' '<< T->data;
PreOder(T->lchild);
PreOder(T->rchild);
}
}
void PostOder(BiTree T)
{
if (T)
{
PostOder(T->lchild);
PostOder(T->rchild);
cout <<' '<< T->data;
}
}
//队列函数
Status InitQueue(SqQueue &Q)
{
Q.base = (QElemtype*)malloc(MAXQSIZE * sizeof(QElemtype));
if (!Q.base) return OVERFLOW;
Q.front = Q.rear = 0;
return OK;
}
Status EnQueue(SqQueue &Q, QElemtype e)
{
if ((Q.rear + 1) % MAXQSIZE == Q.front) return ERROR;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
return OK;
}
Status DeQueue(SqQueue &Q, QElemtype &e)
{
if (Q.front == Q.rear) return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
return OK;
}
Status QeEmpty(SqQueue Q)
{
return Q.front == Q.rear;
}
void LevelOder(BiTree T)//层次遍历
{
SqQueue Q;
QElemtype e;
InitQueue(Q);
if (T)
{
EnQueue(Q, T);
while (!QeEmpty(Q))
{
DeQueue(Q, e);
cout<<' '<< e->data;
if (e->lchild) EnQueue(Q, e->lchild);
if (e->rchild) EnQueue(Q, e->rchild);
}
}
}
int count_n(BiTree T)//结点数目计算
{
int num;
int num1, num2;
if (!T) num = 0 ;
else
{
num1 = count_n(T->lchild);
num2 = count_n(T->rchild);
num = num1 + num2 + 1;
}
return num;
}
int tree_depth(BiTree T)
{
int h, lh, rh;
if (!T) h = 0;
else
{
lh = tree_depth(T->lchild);
rh = tree_depth(T->rchild);
if (lh > rh)
h = lh + 1;
else
h = rh + 1;
}
return h;
}
主函数:
int main()
{
BiTree T;
cout << "请输入数据:";
CreatBitree(T);
cout << "中序遍历:1" << endl << "先序遍历:2" << endl << "后序遍历:3" << endl;
cout << "层次遍历:4" << endl<<"计算结点数目:5"<<endl<<"计算树高度:6"<<endl;
int order;
while (1)
{
cout <<endl<< "输入数据:";
cin >>order;
switch (order)
{
case 1:inOder(T); break;
case 2:PreOder(T); break;
case 3:PostOder(T); break;
case 4:LevelOder(T); break;
case 5:cout<<count_n(T); break;
case 6:cout << tree_depth(T); break;
}
}
system("pause");
}