二叉树的特点:(设结点度为0,1,2的结点个数分别为:n0,n1,n2)
1,每个结点最多只有两个子树;
2,n0-1 = n2 ;
3,边的个数为 n0+n1+n2-1;
4, 结点总数为n的二叉树最少高度为 ,以2为底的log(n+1)上取整
结构体需求:
数据域,指针域(左右孩子指针)
队列:数据域,指针域,队头队尾指针(方便插入与删除)
功能实现:
二叉树的层序遍历:
层序遍历即指二叉树自顶向下进行遍历,而为方便遍历每一层的结点,我们可以利用队列的性质:按照一层一层的方式,放入队列中,出队时将出队元素的孩子结点入队,依次循环,直到树空。
#include <stdio.h>
#include <stdlib.h>
#define End 0//键入值为该值时,二叉树结点为空
typedef int TElemType;
typedef struct BiTNode{//二叉树结构体定义
TElemType Tdata;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
//队列结构体定义
typedef BiTNode *QElemType;
typedef struct QNode{//链队列结点定义
QElemType Qdata;//数列的数据域
struct QNode *next;//链队列的指针域
}QNode,*QueuePtr;
typedef struct{//队头队尾指针
QueuePtr front;
QueuePtr rear;
}LinkQueue;
//方法体
//创建二叉树(使用先序)
BiTree CreateBiTree(BiTree &T){
TElemType in;//设置二叉树结点的键入变量
scanf("%d",&in);
if(in == End){
T = NULL;
}else{//键入值非空结点,开始创建结点插入二叉树中
T = (BiTNode *)malloc(sizeof(BiTNode));
T->Tdata = in;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
return T;
}
//初始化队列,保证队头和队尾指针的稳定性
void InitQueue(LinkQueue &Q){
Q.front = Q.rear = (QNode *)malloc(sizeof(QNode));
Q.front->next = NULL;
}
//队列的入队出队操作(方便进行层序遍历)
void EnQueue(LinkQueue &Q,QElemType e){
QNode *p = (QNode *)malloc(sizeof(QNode));//设置结点,进行插入
p->Qdata = e;
p->next = Q.rear->next;
Q.rear->next = p;
Q.rear = p;//尾指针后移
}
//出队,这里要注意的是,出队元素必须为队列的结点指针类型
//这样方便进行层序遍历,而且可以返回null(若不使用指针,则空结点时不做任何处理即可)
QNode* DeQueue(LinkQueue &Q){
if(Q.rear == Q.front){//若队空,则返回空指针
printf("\n队列为空\n");
return NULL;
}
//队非空,开始出队操作
QNode *d = Q.front->next;//出队的结点
Q.front->next = d->next;//头结点next指针后移
if(d == Q.rear){//若出队结点为最后的结点,则做特殊处理
Q.rear = Q.front;
}
//对删除的结点做所需要的操作
return d;//将出队的结点进行返回
}
//二叉树的层序遍历
void LevelOrderTraserval(BiTree T){
if(T==NULL) { //校验是否为空树
printf("树为空!\n");
return ;
} //树非空,开始创造队列并层序遍历树
LinkQueue Q; //设置队列
InitQueue(Q); //初始化队列
EnQueue(Q,T); //将二叉树的根节点入队
printf("\n该二叉树的层序遍历为:\n");
while(Q.rear != Q.front){ //当队非空时进行遍历
BiTNode *root = DeQueue(Q)->Qdata; //要注意给予的值
printf("%d ",root->Tdata); //输出出队元素的数据
if(root->lchild != NULL) EnQueue(Q,root->lchild);
if(root->rchild != NULL) EnQueue(Q,root->rchild);
}
}
int main(){
BiTree T;
CreateBiTree(T);
LevelOrderTraserval(T);
}