#include<stdio.h>
#include<stdlib.h>
#define ElemType char
#define MAXSIZE 100//栈中
#define SElemType BiTree//非递归栈中要用
#define QElemType BiTree//队列
//构建结点
typedef struct BiTreeNode{
ElemType data;//结点内的数据
BiTreeNode *lchild;//左孩子结点
BiTreeNode *rchild;//右孩子结点
}BiTNode,*BiTree;//指向BiNode类型的指针变量BiTree
//栈
typedef struct{
SElemType data[MAXSIZE];//静态数组存放栈中元素
int top;//栈顶指针
}SqStack;//Sq:sequence顺序
void InitStack(SqStack &S){
S.top = -1;//初始化栈顶指针
}
void PushStack(SqStack &S,SElemType x){
if(S.top == MAXSIZE - 1)//栈满报错
return;
S.data[++S.top] = x;//指针先+1
}
void PopStack(SqStack &S,SElemType &x){
if(S.top == -1)//栈空报错
return;
x = S.data[S.top--];//栈顶元素先出栈,指针-1
}
//队列
typedef struct{
QElemType data[MAXSIZE];//用静态数组存放队列元素
int front,rear;//队头指针和队尾指针
}SqQueue;
void InitQueue(SqQueue &Q){
Q.front = Q.rear = 0;
}
void EnQueue(SqQueue &Q,QElemType x){
Q.data[Q.rear++] = x;
}
void DeQueue(SqQueue &Q,QElemType &x){
if(Q.front == Q.rear)
return;
x = Q.data[Q.front++];
}
//访问函数
void visit(BiTree T){
printf("%c",T->data);
}
//创建树
void CreateTree(BiTree &T){
printf("请输入结点:\n");
char ch = getchar();//读取输入的字符
getchar();//吃掉回车
if(ch == ' '){//输入空格代表NULL
T = NULL;
}
else{
T = (BiTree)malloc(sizeof(BiTNode));//T为BiTree类型,是指向BiTNode的指针,给他malloc一个BiTNode结构体
T->data = ch;
CreateTree(T->lchild);//遍历
CreateTree(T->rchild);
}
}
//前序递归遍历
void PreOrder(BiTree T){
if(T){
visit(T);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
//中序递归遍历
void InOrder(BiTree T){
if(T){
InOrder(T->lchild);
visit(T);
InOrder(T->rchild);
}
}
//后序递归遍历
void PostOrder(BiTree T){
if(T){
PostOrder(T->lchild);
PostOrder(T->rchild);
visit(T);
}
}
//层次遍历(队列)
void LevelOrder(BiTree T){
SqQueue Q;
QElemType x;
InitQueue(Q);
EnQueue(Q,T);
while(Q.front != Q.rear){
DeQueue(Q,x);
printf("%c",x->data);
if(x->lchild){
EnQueue(Q,x->lchild);
}
if(x->rchild){
EnQueue(Q,x->rchild);
}
}
}
//前序非递归遍历(栈)
void Pre(BiTree T){
SqStack S;
SElemType x;
InitStack(S);
PushStack(S,T);
while(S.top != -1){
PopStack(S,x);
printf("%c",x->data);
if(x->rchild){
PushStack(S,x->rchild);
}
if(x->lchild){
PushStack(S,x->lchild);
}
}
}
//判断树中叶子结点个数
int yezi(BiTree &T){
static int yznum = 0;
if(T->lchild || T->rchild){
if(T->lchild) yezi(T->lchild);
if(T->rchild) yezi(T->rchild);
}
else yznum++;
return yznum;
}
//判断树的深度
int GetDepth(BiTree &T){
static int depth = 0;
if(T == NULL) return 0;
int leftdepth = GetDepth(T->lchild);
int rightdepth = GetDepth(T->rchild);
depth = 1 + (leftdepth>rightdepth?leftdepth:rightdepth);
return depth;
}
int main(){
BiTree T;//T表示根节点
CreateTree(T);
LevelOrder(T);
return 0;
}
二叉树——递归、非递归遍历,深度,叶子结点个数(C语言实现)
于 2023-12-02 20:04:40 首次发布