题目描述
已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。
输入
输入一个长度小于50个字符的字符串。
输出
输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
示例输入
abc,,de,g,,f,,,
示例输出
cbegdfacgefdba35下面求深度改了点东西求深度#include<stdio.h> #include<malloc.h> #include<string.h> typedef struct node { char data; node *lch, *rch; } q,*p; int sum=0; void creat(p &head)//建立二叉树这里&head传递的是地址因为要改变地址也可以直接建立链表这里是“引用”; { char ch; scanf("%c",&ch); if (ch == ',') head = NULL; else { head = new node; head->data = ch; creat(head->lch); creat(head->rch); } } void find1(p head) { if(head) { find1(head->lch); printf("%c",head->data); find1(head->rch); } } void find2(p head) { if(head) { find2(head->lch); find2(head->rch); printf("%c",head->data); } } int count2(p t)//计数当最后一个值没有孩子时便+1; { if(t) { if(t->lch==NULL&&t->rch==NULL) { sum++; } if(t->lch) count2(t->lch); if(t->rch) count2(t->rch); } } int getdepth(p head)//求深度这里是每次判断当到最后时return 0;所以nl=0;nr=0;然后下面依次返回if(nl>nr)return nl+1; else return nr+1;然后每次加一 { int depth=0; if(!head) return 0; int nl=getdepth(head->lch); int nr=getdepth(head->rch); if(nl>nr) return nl+1; else return nr+1; } int main() { p head; int a; creat(head); find1(head); printf("\n"); find2(head); printf("\n"); count2(head); printf("%d\n",sum); a=getdepth(head); printf("%d\n",a); return 0; }
下面避免了引用#include<stdio.h> #include<malloc.h> #include<string.h> typedef struct node { char data; node *lch, *rch; } q,*p; int sum=0,ma=0; void creat(p &head) { char ch; scanf("%c",&ch); if (ch == ',') head = NULL; else { head = new node; head->data = ch; creat(head->lch); creat(head->rch); } } void find1(p head) { if(head) { find1(head->lch); printf("%c",head->data); find1(head->rch); } } int find2(p head,int d) { if(head) { find2(head->lch,d+1); find2(head->rch,d+1); printf("%c",head->data); if(ma<d) ma=d; } } int count2(p t) { if(t) { if(t->lch==NULL&&t->rch==NULL) { sum++; } if(t->lch) count2(t->lch); if(t->rch) count2(t->rch); } } int main() { p head; int a=0; creat(head); find1(head); printf("\n"); find2(head,a); printf("\n"); count2(head); printf("%d\n",sum); printf("%d\n",ma+1); return 0; }
#include <stdio.h> #include <stdlib.h> typedef struct linshi { char ch; struct linshi *lzz; struct linshi *rzz; }ls; ls *jlg()//这里返回的是指针所以用这样 { char a='\0'; ls *t=(ls *)malloc(sizeof(struct linshi)*1); t->ch='\0'; t->lzz=NULL; t->rzz=NULL; scanf("%c",&a); if(a!=',') { t->ch=a; t->lzz=jlg(); t->rzz=jlg(); } else { t= NULL; } return t; } void xxseach(ls *f) { if(f) { printf("%c",f->ch); zxseach(f->lzz); zxseach(f->rzz); } } void zxseach(ls *f) { if(f) { zxseach(f->lzz); printf("%c",f->ch); zxseach(f->rzz); } } void hxseach(ls *f) { if(f) { hxseach(f->lzz); hxseach(f->rzz); printf("%c",f->ch); } } int main() { ls *g; g=jlg(); xxseach(g); printf("\n"); zxseach(g); printf("\n"); hxseach(g); printf("\n"); return 0; }