实验四、5非递归创建遍历二叉树

/*非递归创建二叉树并遍历二叉树*/
#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);
}
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值