数据结构二叉树遍历及线索化后各种操作(绝对无错).docxVIP

  • 5
  • 0
  • 约2.99千字
  • 约 16页
  • 2020-03-26 发布于江西
  • 举报

数据结构二叉树遍历及线索化后各种操作(绝对无错).docx

实验二 二叉树的存储结构及各种运算的实现 第一题: #include stdio.h #include malloc.h #define maxsize 66 typedef int datatype; typedef struct node { datatype data ; struct node *lchild,*rchild; } bitree; bitree *Q[maxsize]; bitree *creatree() { char ch; int front,rear; bitree *root,*s; root=NULL; front=1;rear=0; ch=getchar(); while (ch!=#) { s=NULL; if(ch!=@) { s=malloc(sizeof(bitree)); s-data=ch; s-lchild=NULL; s-rchild=NULL; } rear++; Q[rear]=s; if(rear==1) root=s; else { if (sQ[front]) if(rear%2==0) Q[front]-lchild=s; else Q[front]-rchild=s; if(rear%2==1) front++; } ch=getchar(); } return root; } preorder(bitree *t) //前 { if (t) { printf( %c ,t-data); preorder(t-lchild); preorder(t-rchild); } } inorder(bitree *t) //中 { if (t) { inorder(t-lchild); printf( %c ,t-data); inorder(t-rchild); } } postorder(bitree *t) //后 { if (t) { postorder(t-lchild); postorder(t-rchild); printf( %c ,t-data); } } int height(bitree *t) //高度 { int hl,hr; if(!t) return 0; else { hl=height(t-lchild); hr=height(t-rchild); return ((hlhr?hl:hr)+1); } } int leaf(bitree *t) //叶子 { static int s; if(t) { leaf(t-lchild); leaf(t-rchild); if(t-lchild==NULLt-rchild==NULL) s=s+1; } return s; } main() { bitree *t; int x,y; printf(输入数据,以#做结尾:\n); t=creatree(); printf(preorder:\t);preorder(t); printf(\ninorder:\t);inorder(t); printf(\npostorder:\t);postorder(t); =height(t); =leaf(t); printf(\n 高度:%d,x); printf(\n 叶子:%d,y); printf(\n); } 第二题: #include stdio.h #include malloc.h #define maxsize 40 typedef struct node{ char data; struct node *lchild,*rchild; int ltag,rtag; } bitree; bitree *Q[maxsize]; /*队列*/ bitree *pre=NULL; bitree *creatree() { char ch; int front,rear; /*队头、队尾*/ bitree *root,*s; root=NULL; /*空树*/ front=1; rear=0; /*空队*/ ch=getchar(); while(ch!=#) { s=NULL; if(ch!=@) /*建立新结点*/ { s=(bitree *)malloc(sizeof(bitree)); s-data=ch; s-lchild=s-rchild=NULL; s-ltag=s-rtag=0; } rear++; Q[rear]=s; /*入队*/ if(rear==1) root=s; else { if(s Q[front]) /*孩子、双亲均非空*/ if(rear%2==0) Q[front]-lchild=s; else Q[front]-rchild=s; if(rear%2

文档评论(0)

1亿VIP精品文档

相关文档