1、程序代码
#include <stdio.h>
#include <stdlib.h>
typedef struct tree{
int data;
struct tree *lchild;
struct tree *rchild;
}tree_t;
typedef tree_t *data_t;
typedef struct node{
data_t data;
struct node *next;
}node_t;
typedef struct lqueue{
struct node *front;
struct node *rear;
}lqueue_t;
//1.创建空队列
lqueue_t *createlqueue(void)
{
lqueue_t *head=(lqueue_t *)malloc(sizeof(lqueue_t));//给头节点申请空间
if(NULL==head)
return NULL;
head->front=(node_t *)malloc(sizeof(node_t));
if(NULL==head->front)
return NULL;
head->rear=head->front;
head->front->next=NULL;
return head;
}
//2.创建完全二叉树
tree_t *creatBinTree(int i,int n)//i:节点编号,n:节点个数
{
tree_t *root=(tree_t *)malloc(sizeof(tree_t));
if(NULL==root)
return NULL;
root->data=i;
if(2*i<=n)//判断root节点是否有左节点
root->lchild=creatBinTree(2*i,n);
else//无左节点
root->lchild=NULL;
if(2*i+1<=n)//判断root节点是否有右节点
root->rchild=creatBinTree(2*i+1,n);
else//无右节点
root->rchild=NULL;
return root;
}
//3.判空
int lqueue_is_empty(lqueue_t *lq)
{
if(NULL!=lq)
return(lq->front==lq->rear?1:0);
else
return -1;
}
//4.入队,队尾入队
int enlqueue(lqueue_t *lq,data_t data)
{
if(lq==NULL)
return -1;
//1)创建新节点
node_t *new=(node_t *)malloc(sizeof(node_t));
if(NULL==new)
return -1;
new->data=data;
new->next=NULL;
//2)队尾入队
lq->rear->next=new;
lq->rear=lq->rear->next;
return 0;
}
//5.出队,队头出队(pos=0的位置)
data_t delqueue(lqueue_t *lq)
{
//1)判空
if(lqueue_is_empty(lq))
return NULL;
//2)出队
node_t *p=lq->front->next;//p指向队头节点
lq->front->next=p->next;
data_t data=p->data;
free(p);
p=NULL;
if(lq->front->next==NULL)//判断是否为空
lq->rear=lq->front;
return data;
}
//递归遍历二叉树:6、7、8:
//6.先序遍历
void DLR(tree_t *root)
{
if(NULL==root)
return;
printf("%d ",root->data);
DLR(root->lchild);
DLR(root->rchild);
}
//7.中序遍历
void LDR(tree_t *root)
{
if(NULL==root)
return;
LDR(root->lchild);
printf("%d ",root->data);
LDR(root->rchild);
}
//8.后序遍历
void LRD(tree_t *root)
{
if(NULL==root)
return;
LRD(root->lchild);
LRD(root->rchild);
printf("%d ",root->data);
}
//9.非递归遍历二叉树:层次遍历
void LEV(tree_t *root)
{
if(NULL==root)
return;
//1)创建队列
lqueue_t *lq=createlqueue();
if(lq==NULL)
return;
//2)根节点入队
enlqueue(lq,root);
//3)循环判断队列是否为空
while(lqueue_is_empty(lq)!=1)
{
tree_t *root=delqueue(lq);
printf("%d ",root->data);
//4)判断是否有左孩子
if(root->lchild !=NULL)
enlqueue(lq,root->lchild);
//5)判断是否有右孩子
if(root->rchild !=NULL)
enlqueue(lq,root->rchild);
}
return;
}
//10.主函数
int main(int argc, char *argv[])
{
tree_t *root=creatBinTree(1,10);
if(NULL==root)
{
printf("malloc failed\n");
return -1;
}
printf("先序遍历二叉树:\n");
DLR(root);
printf("\n");
printf("中序遍历二叉树:\n");
LDR(root);
printf("\n");
printf("后序遍历二叉树:\n");
LRD(root);
printf("\n");
printf("层次遍历二叉树:\n");
LEV(root);
printf("\n");
return 0;
}
2、运行结果: