/*非递归创建二叉树并遍历二叉树*/
#include<stdio.h>
#include<stdlib.h>
#define null 0
#define max 20//结点数定义为20
#define elemtype char
typedef struct bnode//二叉树结点类型
{
elemtype date;
struct bnode *lc,*rc;
}btnode;
typedef struct qnode//结点指针队列
{
btnode *qd[max];
int front,rear;
}queue;
queue *sq;
typedef struct snode//二叉树结点类型=栈
{
btnode *sd[max];
int top;
}stack;
stack *st;
btnode *creatnode(elemtype x)//将x作为数据域创建一个结点
{
btnode *p;
p=(btnode*)malloc(sizeof(btnode));
p->date=x;
p->lc=null;
p->rc=null;
return(p);
}
btnode *creattree()//用非递归方法创建一个二叉树
{
btnode *t,*p,*q;
elemtype ch;
int i=0;//计数器
t=null;//t为指向二叉树根结点的指针
sq->front=-1;//初始化队列
sq->rear=-1;
printf("请输入一个字符串:");
ch=getchar();//接收输入的字符
while( if(p->lc==null)//做孩子存在则入对
if((rear+1)!=front)
{
queue[rear]=p->lc;
rear=(rear+1)%m;
}
if(p->rc==null)//有孩子存在入队
if((rear+1)!=front)
{
queue[rear]=p->rc;
rear=(rear+1)%m;
}
}
}
void xiangen(btnode *t)//对t指向的二叉树进行先跟遍历
{
btnode *p;
st->top=-1;//初始化栈为空
if(t)//若二叉树不为空 则将其根节点入栈
st->sd[st->top]=t;
while(st->top!=-1)//栈布控时 出战 p指向栈顶元素
{
p=st->sd[st->top--];
while(p)//当出战元素不为空时 访问他 继续搜索坐子树 右子树入栈
{
printf("%c->",p->date);
if(p->rc)
st->sd[++st->top]=p->rc;
p=p->lc;
}
}
}
void zhonggen(btnode *t)
{
btnode *p;
st->top=-1;
if(t)
st->sd[++st->top]=t;
while(st->top!=-1)
{
p=st->sd[st->top];
while(p)
{
st->sd[++st->top]=p->lc;
p=p->lc;
}
p=st->sd[--st->top];
if(st->top!=-1)
{
p=st->sd[st->top--];
printf("%c->",p->date);
st->sd[++st->top]=p->rc;
}
}
}
int main()
{
btnode *bt;
int n;
//clrscr();
printf("请输入节点数:/n");
scanf("%d",&n);
//getchar();
bt=creattree();
printf("层次遍历是:");
cengci(bt,n);
printf("/n");
printf("先跟遍历是:");
xiangen(bt);
printf("/n");
printf("中跟遍历是:");
zhonggen(bt);
}
实验四、5非递归创建遍历二叉树
最新推荐文章于 2022-04-26 16:10:58 发布