您的位置:首页 > 其它

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

2009-06-17 09:55 423 查看
/*非递归创建二叉树并遍历二叉树*/

#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(ch!='@')//当是@时停止创建

 {

  p=null;

  if(ch!='#')//如果不是空结点创建一个结点

   p=creatnode(ch);//p指向新结点

  i++;//结点计数器

  sq->qd[++sq->rear]=p;//新结点指针入队列

  if(sq->front==-1)//如果是第一个结点入对,则将对头指针指向第一个结点

   sq->front++;

  if(i==1)

   t=p;//t指向跟结点

  else

  {

   q=sq->qd[sq->front] ;//q指向队首元素指向的结点

   if(p&&q)

    if(i%2==0)

     q->lc=p;

   else

    q->rc=p;

   if(i%2==1)

    sq->front++;

  }

  ch=getchar();

 }

 return (t);

}

void cengci(btnode *t,int m)//对含有m个结点的二叉树t进行层次遍历

{

 btnode *queue[max];

 btnode *p;

 int front=0,rear=0,i;

 queue[rear++]=t;//根结点入对

 while(front!=rear)//不空时进行遍历

 {

  p=queue[front];//p指向队首元素

  front=(front+1)%m;//队首元素出栈

  printf("%c->",p->date);

  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);

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: