二叉树的创建及遍历(一级指针)

#include<stdio.h>
#include<malloc.h>
#include<stdbool.h>
#define QUEUESIZE 5

typedef struct BiNode{
	char data;
	struct BiNode *lchild, *rchild;
}BiNode;

typedef struct{
	BiNode *d[QUEUESIZE];				//指向队列存储空间 
	int front;							//队首下标 
	int rear;							//队尾下标 
}Queue;

bool isFull(Queue *);
bool isEmpty(Queue *);
void initCirQueue(Queue *);

void initCirQueue(Queue *q){
	q->front=QUEUESIZE-1;
	q->rear=-1;
}

bool enQueue(Queue *q,BiNode *bt){		//入队 
	if(!isFull(q)){
		q->rear=(q->rear+1)%QUEUESIZE;
		q->d[q->rear]=bt;
		return true;
	}else
		return false;
}

BiNode* deQueue(Queue *q,BiNode **p){	//出队 
	if(!isEmpty(q)){
		q->front=(q->front+1)%QUEUESIZE;
		*p=q->d[q->front];
		return true;
	}else
		return false;
}

bool isFull(Queue *q){					//判断队列是否为满 
	if((q->rear+1)%QUEUESIZE==q->front)
		return true;
	else
		return false;
}

bool isEmpty(Queue *q){
	if(q->rear==-1||q->front==q->rear)
		return true;
	else
		return false;
}

char getval(char *str){
	static int i=0;
	return str[i++];					//*(str+i++);
}

BiNode * create(BiNode *bt,char *str){	//创建二叉树
	char ch=getval(str); 
	if(ch=='#'){
		bt=NULL;
	}else{
		bt=(BiNode *)malloc(sizeof(BiNode));
		bt->data=ch;
		bt->lchild=create(bt->lchild,str);
		bt->rchild=create(bt->rchild,str);
	}
	return bt;
}

void release(BiNode **bt){				//销毁二叉树 
	if(*bt==NULL){
		return;
	} 
	else{
		release(&((*bt)->lchild));
		release(&((*bt)->rchild));
		free(*bt);
		*bt=NULL;
	}
}

void preOrder(BiNode *bt){				//前序遍历 
	if(bt==NULL){
		printf("#");
		return;
	} 
	else{
		printf("%c",bt->data);
		preOrder(bt->lchild);
		preOrder(bt->rchild); 
	}
}

void inOrder(BiNode *bt){				//中序遍历 
	if(bt==NULL){
		printf("#");
		return;
	} 
	else{
		inOrder(bt->lchild);
		printf("%c",bt->data);
		inOrder(bt->rchild); 
	}
}

void postOrder(BiNode *bt){				//后续遍历 
	if(bt==NULL){
		printf("#");
		return;
	} 
	else{
		postOrder(bt->lchild);
		postOrder(bt->rchild);
		printf("%c",bt->data);
	}
}

void leverOrder(BiNode *bt){			//层序遍历
	Queue q;
	BiNode *p;
	initCirQueue(&q);					//初始化队列 
	enQueue(&q,bt);						//根节点指针入队 
	while(!isEmpty(&q)){				//队不为空,则循环 
		deQueue(&q,&p);					//出队节点p 
		printf("%c",p->data);			//访问节点p 
		if(p->lchild!=NULL)
			enQueue(&q,p->lchild);		//有左孩子时将其入队 
		if(p->rchild!=NULL)
			enQueue(&q,p->rchild); 		//有右孩子时将其入队 
	}
}

int main(void){
	char *str="ABC##DE#G##F###";
	BiNode * root=create(root,str);
	preOrder(root);
	printf("\n"); 
	inOrder(root);
	printf("\n"); 
	postOrder(root);
	printf("\n");
	leverOrder(root);
	release(&root);
	printf("\n"); 
	preOrder(root);
	return 0;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值