首先是结构体的定义
typedef struct node
{
struct node *leftChild;
struct node *rightChild;
char data;
}BiTreeNode, *BiTree;
二叉树的四种遍历(先序,中序,后序,层次)
1.先序
void printTree3(BiTree &T){//xian
if(T==NULL){
return ;
}else{
printf("%c",T->data);
printTree2(T->leftChild);
printTree2(T->rightChild);
}
}
2.中序
void printTree1(BiTree &T){//zhong
if(T==NULL){
return;
}else{
printTree1(T->leftChild);
printf("%c",T->data);
printTree1(T->rightChild);
}
}
3.后序
void printTree2(BiTree &T){//hou
if(T==NULL){
return ;
}else{
printTree2(T->leftChild);
printTree2(T->rightChild);
printf("%c",T->data);
}
}
4.层次遍历
//第一种写法
void PrintAtLevel(Tree T) {
queue myqueue;
myqueue.push(T);
while (!myqueue.empty()) {
Tree tmp = myqueue.front();
if (tmp->lchild != NULL)
myqueue.push(tmp->lchild);
if (tmp->rchild != NULL)
myqueue.push(tmp->rchild);
cout << tmp->value << " ";
myqueue.pop();
}
}
//第二种写法
void LevelOrderTraversal(Ptree BT)
{
Queue Q;
Ptree T;
if(!BT) return;
Q=CreateQueue();
T=BT;
InsertQ(T,Q);
while(!IsEmpty(Q)){
T=DeleteQ(Q);
printf("%c",T->data);
if(T->lchild) InsertQ(T->lchild,Q);
if(T->rchild) InsertQ(T->rchild,Q);
}
};
//第三种
void LevleOrder(BiTree T)
{ /*层次遍历二叉树T,从第一层开始,每层从左到右*/
BiTree Queue[MAX],b;/*用一维数组表示队列,front和rear分别表示队首和队尾指针*/
int front,rear;
front=rear=0;
if(T) /*若树非空*/
{
Queue[rear++]=T; /*根结点入队列*/
while (front!=rear)
{ /*当队列非空*/
b=Queue[front++]; /*队首元素出队列,并访问这个结点*/
printf("%2c",b->data);
if(b->lchild!=NULL) Queue[rear++]=b->lchild; /*左子树非空,则入队列*/
if(b->rchild!=NULL) Queue[rear++]=b->rchild; /*右子树非空,则入队列*/
}
}
}/*LevelOrder*/