.h文件
#include <stdio.h>
#include <stdlib.h>
struct biTree{
char data;
struct biTree * lchild, * rchild;
};
struct biTree * initBiTree();
struct biTree * createBiTree(struct biTree * bt);
int preOrderTraverse(struct biTree * bt);
int inOrderTraverse(struct biTree * bt);
int postOrderTraverse(struct biTree * bt);
int levelOrderTraverse(struct biTree * bt);
.c文件
#include "二叉树.h"
#define MAX 100
struct biTree * initBiTree(){
struct biTree * bt;
bt=(struct biTree *)malloc(sizeof(struct biTree));
bt->lchild=NULL;
bt->rchild=NULL;
return bt;
}
struct biTree * createBiTree(struct biTree * bt){//先序创建二叉树
char ch;
ch=getchar();
if(ch=='#'){
bt=NULL;
}
else{
bt=(struct biTree *)malloc(sizeof(struct biTree));
bt->data=ch;
bt->lchild=createBiTree(bt->lchild);
bt->rchild=createBiTree(bt->rchild);
}
return bt;
}
int preOrderTraverse(struct biTree * bt){
if(bt!=NULL){
printf("%c ",bt->data);
preOrderTraverse(bt->lchild);
preOrderTraverse(bt->rchild);
}
return 0;
}
int inOrderTraverse(struct biTree * bt){
if(bt!=NULL){
inOrderTraverse(bt->lchild);
printf("%c ",bt->data);
inOrderTraverse(bt->rchild);
}
return 0;
}
int postOrderTraverse(struct biTree * bt){
if(bt!=NULL){
postOrderTraverse(bt->lchild);
postOrderTraverse(bt->rchild);
printf("%c ",bt->data);
}
return 0;
}
int levelOrderTraverse(struct biTree * bt){
struct biTree * Queue[MAX],* p;
int front,rear;
front=rear=0;
if(bt!=NULL){
Queue[rear]=bt;
rear++;
while(front!=rear)
{
p=Queue[front];
front++;
printf("%c ",p->data);
if(p->lchild!=NULL){
Queue[rear]=p->lchild;
rear++;
}
if(p->rchild!=NULL){
Queue[rear]=p->rchild;
rear++;
}
}
}
return 0;
}
int main(){
struct biTree * bt;
bt=initBiTree();
bt=createBiTree(bt);
preOrderTraverse(bt);
printf("\n");
inOrderTraverse(bt);
printf("\n");
postOrderTraverse(bt);
printf("\n");
levelOrderTraverse(bt);
return 0;
}
二叉树(先序创建,前中后序及按层遍历)
最新推荐文章于 2023-02-28 21:39:17 发布