现在的位置: 首页 > 综合 > 正文

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

2013年10月07日 ⁄ 综合 ⁄ 共 987字 ⁄ 字号 评论关闭

/*
  Description: 用递归方法进行二叉树的创建,先跟,中根,后跟遍历
*/

#include<stdio.h>
#include<stdlib.h>
#define null 0
typedef struct btnode//二叉树结点类型
{
 char date;
 struct btnode *lc,*rc; 
}bttree;
bttree *creattree()//创建二叉树并将而二叉树的跟结点指针返回
{
 //getchar();
 bttree *p;
 char ch;
 if((ch=getchar())=='#')//当输入不是  时创建结点p
  p=null;
 else
 {
  p=(bttree*)malloc(sizeof(bttree));
  p->date=ch;
  p->lc=creattree();
  p->rc=creattree(); 
 }
 return(p);
}
void xiangen(bttree *p)//对p指向的二叉树进行先跟遍历
{
 if(p!=null)
 {
  printf("%2c",p->date);
  xiangen(p->lc);
  xiangen(p->rc); 
 }
}
void zhonggen(bttree *p)//中根遍历
{
 if(p!=null)
 {
  zhonggen(p->lc);
  printf("%2c",p->date);
  zhonggen(p->rc);
 } 
}
void hougen(bttree *p)//后跟遍历
{
 if(p!=null)
 {
  hougen(p->lc);
  hougen(p->rc);
  printf("%2c",p->date);
 } 
}
int main()//主函数
{
 bttree *p;
 printf("请输入字符以‘#’结束:");//输入时例如创建 二叉树abc根是a,bc分别是左右子树,则输入格式是ab##c##然后回车即可
 //p=null;
 p=creattree();
 printf("先跟遍历是:/n");
 xiangen(p);
 printf("/n");
 printf("中跟遍历是:/n");
 zhonggen(p);
 printf("/n");
 printf("后跟遍历是:/n");
 hougen(p);
 printf("/n");
 system("pause");
}
 

抱歉!评论已关闭.