#include<stdio.h>
#include<stdlib.h>
typedef struct BitNode
{
char data;
struct BitNode *lchild,*rchild;
}BitNode;
BitNode* CreateBiT() //建立二叉树
{
char ch;
BitNode *T;
scanf("%c",&ch);
if(ch == ' ') T = NULL;
else{
T = (BitNode*)malloc(sizeof(BitNode));
T->data = ch;
T->lchild = CreateBiT();
T->rchild = CreateBiT();
}
return T;
}
void Preorder (BitNode *T) //先序遍历
{
if(T)
{
printf("%c",T->data);
Preorder(T->lchild);
Preorder(T->rchild);
}
else return;
}
void Infixorder (BitNode *T) //中序遍历
{
if(T)
{
Infixorder(T->lchild);
printf("%c",T->data);
Infixorder(T->rchild);
}
else return;
}
void Epilogue (BitNode *T) //后序遍历
{
if(T)
{
Epilogue(T->lchild);
Epilogue(T->rchild);
printf("%c",T->data);
}
else return;
}
void levelOrder(BitNode *T) //利用队列层次遍历
{
BitNode *Q[100];
int rear,front;
BitNode *p;
rear = front = 0;
Q[rear] = T;
rear = (rear+1)%100;
while((rear+1)%100 != front)
{
p = Q[front];
printf("%c",p->data);
front = (front+1)%100;
if(p->lchild)
{
Q[rear] = p->lchild;
rear = (rear+1)%100;
}
if(p->rchild)
{
Q[rear] = p->rchild;
rear = (rear+1)%100;
}
}
}
int main()
{
BitNode *T;
printf("请输入节点的value(在一行输入):");
T = CreateBiT();
printf("\n先序:");
Preorder (T);
printf("\n中序:");
Infixorder(T);
printf("\n后序:");
Epilogue(T);
printf("\n层次:");
levelOrder(T);
return 0;
}
二叉树的建立与遍历(先序,中序,后序,层次)
猜你喜欢
转载自blog.csdn.net/weixin_43260290/article/details/84531363
今日推荐
周排行