数据结构实验之二叉树的建立与遍历
Time Limit: 1000MS Memory limit: 65536K
题目描述
已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。
输入
输入一个长度小于50个字符的字符串。
输出
输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
示例输入
abc,,de,g,,f,,,
示例输出
cbegdfacgefdba35
数组建二叉树 #include<stdio.h> #include<string.h> struct list { char ch; int l; int r; }num[1000001]; int ns=0; int creat()//创建一个二叉树,返回根节点的编号 { ns++; char st; int p=ns; scanf("%c",&st); if(st==',')return -1; else { num[p].ch=st; num[p].l=creat(); num[p].r=creat(); return p; } } void printmid(int rt)//中序输出二叉树 { if(num[rt].l!=-1)printmid(num[rt].l); printf("%c",num[rt].ch); if(num[rt].r!=-1)printmid(num[rt].r); } void printhigh(int rt)//后序输出二叉树 { if(num[rt].l!=-1)printhigh(num[rt].l); if(num[rt].r!=-1)printhigh(num[rt].r); printf("%c",num[rt].ch); } int printleave(int rt)//求叶子节点的个数 { int aa; aa=0; if(num[rt].l==-1&&num[rt].r==-1)return 1; if(num[rt].l!=-1)aa+=printleave(num[rt].l); if(num[rt].r!=-1)aa+=printleave(num[rt].r); return aa; } int printdeep(int rt)//求二叉树的深度 { int aa,ll,rr; aa=ll=rr=0; if(num[rt].l==-1&&num[rt].r==-1)return 1; if(num[rt].l!=-1)ll=printdeep(num[rt].l); if(num[rt].r!=-1)rr=printdeep(num[rt].r); aa=ll>rr?ll:rr; return aa+1; } int main() { int root=creat(); printmid(root); printf("\n"); printhigh(root); printf("\n"); printf("%d\n",printleave(root)); printf("%d\n",printdeep(root)); return 0; }
链表建二叉树 #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { char a; struct node *l,*r; }*tree; struct node *creat(node *&p) { char ch; scanf("%c",&ch); if(ch==',') return NULL; else { p=(struct node*)malloc(sizeof(struct node)); p->a=ch; p->l=creat(p->l); p->r=creat(p->r); return p; } } void printfmid(struct node *&p) { if(p==NULL) return ; printfmid(p->l); printf("%c",p->a); printfmid(p->r); } void printflate(struct node *&p) { if(p==NULL) return ; printflate(p->l); printflate(p->r); printf("%c",p->a); } int printfleave(struct node *&p) { int aa=0; if(p->l==NULL&&p->r==NULL) return 1; if(p->l!=NULL) aa+=printfleave(p->l); if(p->r!=NULL) aa+=printfleave(p->r); return aa; } int printfdeep(struct node *&p) { int aa,ll,rr; aa=ll=rr=0; if(p->l==NULL&&p->r==NULL) return 1; if(p->l!=NULL) ll=printfdeep(p->l); if(p->r!=NULL) rr=printfdeep(p->r); aa=ll>rr?ll:rr; return aa+1; } int main() { struct node *head; head=creat(head); printfmid(head); printf("\n"); printflate(head); printf("\n"); printf("%d\n",printfleave(head)); printf("%d\n",printfdeep(head)); return 0; }