/*
* 读取字符串abcdefghij,然后层次建树建立一颗二叉树,然后中序遍历输出 hdibjeafcg,
* 后序遍历输出 hidjebfgca,层序遍历输出abcdefghij,注意不要输出汉字*/
#include <stdio.h>
#include <stdlib.h>
#define BiType char
#define ElementType BiTree
typedef struct BiNode{
BiNode* left;
BiType data;
BiNode* right;
}BiNode,*BiTree;
typedef struct LinkNode{
ElementType data;
LinkNode* next;
}LinkNode,*LinkList;
typedef struct Queue{
LinkNode* front;
LinkNode* rear;
};
void initQueue(Queue &Q){
LinkList L=(LinkNode*) malloc(sizeof(LinkNode));
Q.front=Q.rear=L;
}
void EnQueue(Queue &Q,LinkNode* ele){
LinkNode *NewNode=(LinkNode*) malloc(sizeof(LinkNode));
NewNode=ele;
NewNode->next=NULL;
Q.rear->next=NewNode;
Q.rear=Q.rear->next;
}
void DeQueue(Queue &Q,LinkNode* &delEle){
if(Q.rear==Q.front){
printf("the queue is empty");
}
else{
delEle=Q.front->next;
free(Q.front);
Q.front=delEle;
}
}
bool isEmpty(Queue Q){
if(Q.front==Q.rear){
return true;
}
else{
return false;
}
}
void BuildTree(BiTree &root,Queue &Q){
root=(BiNode*) malloc(sizeof(BiNode));
root=Q.front->next->data;
BiNode *biNode=root;
//Q.front指向元素为空
LinkNode *ChildNode=Q.front->next->next;
LinkNode* delEle;
while (ChildNode){
if (!biNode->left){
biNode->left=ChildNode->data;
ChildNode=ChildNode->next;
}
//需加入判断,防止结束的时候右节点没有孩子,将NULL插入到右节点发生错误
if (!biNode->right&&ChildNode){
biNode->right=ChildNode->data;
ChildNode=ChildNode->next;
}
if (biNode->right&&biNode->right){
DeQueue(Q,delEle);
biNode=Q.front->next->data;
}
}
}
void PreOrder(BiTree tree){
if (tree){
printf("%c",tree->data);
PreOrder(tree->left);
PreOrder(tree->right);
}
}
void InOrder(BiTree tree){
if (tree){
InOrder(tree->left);
printf("%c",tree->data);
InOrder(tree->right);
}
}
void PostOrder(BiTree tree){
if(tree){
PostOrder(tree->left);
PostOrder(tree->right);
printf("%c",tree->data);
}
}
void LevelOrder(BiTree tree,Queue Q){
BiNode *pNode=tree;
LinkNode *Node=(LinkNode*) calloc(1,sizeof(LinkNode));
Node->data=pNode;
EnQueue(Q, Node);
LinkNode *delNode;
while(!isEmpty(Q)){
DeQueue(Q,delNode);
printf("%c",delNode->data->data);
if(pNode->left){
LinkNode *newNode=(LinkNode*) calloc(1,sizeof(LinkNode));
newNode->data=pNode->left;
EnQueue(Q,newNode);
}
if(pNode->right){
LinkNode *newNode1=(LinkNode*) calloc(1,sizeof(LinkNode));
newNode1->data=pNode->right;
EnQueue(Q,newNode1);
}
//防止队列为空的时候Q.front=Q.rear,Q.front->next->data造成内存泄露
if(Q.front->next){
pNode=Q.front->next->data;
}
}
return;
}
int main() {
Queue Q;
BiTree tree;
initQueue(Q);
char c;
for(int i=0;i<10;i++){
LinkNode *Lnode=(LinkNode*) malloc(sizeof(LinkNode));
BiNode* Binode=(BiNode*) malloc(sizeof(BiNode));
scanf("%c",&c);
Binode->data=c;
Binode->left=Binode->right=NULL;
Lnode->data=Binode;
EnQueue(Q,Lnode);
}
BuildTree(tree,Q);
// PreOrder(tree);
InOrder(tree);
printf("\n");
PostOrder(tree);
printf("\n");
Queue Q1;
initQueue(Q1);
LevelOrder(tree,Q1);
return 0;
}
二叉树的层次遍历
最新推荐文章于 2024-04-27 10:12:52 发布