数据结构实验之二叉树的建立与遍历
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
提示
来源
ma6174
示例程序
- #include<stdio.h>
- #include<string.h>
- struct node
- {
- char data;
- struct node *l, *r;
- };
- struct node *build(struct node *t)
- {
- char x;
- scanf("%c", &x);
- if(x!=',')
- {
- t=new node;
- t->data=x;
- t->l=build(t->l);
- t->r=build(t->r);
- }
- else
- t=NULL;
- return t;
- };
- void mid(struct node *t)
- {
- if(t!=NULL)
- {
- mid(t->l);
- printf("%c", t->data);
- mid(t->r);
- }
- }
- void last(struct node *t)
- {
- if(t!=NULL)
- {
- last(t->l);
- last(t->r);
- printf("%c", t->data);
- }
- }
- int ans=0;
- void leaf(struct node *p)
- {
- if(p)
- {
- if(p->l==NULL && p->r==NULL)
- {
- ans++;
- }
- leaf(p->l);
- leaf(p->r);
- }
- }
- int dptree(struct node *p)
- {
- if(!p)
- return 0;
- else if(p)
- {
- int dl=dptree(p->l);
- int dr=dptree(p->r);
- return dl>dr ? dl+1 : dr+1;
- }
- return 0;
- }
- int main()
- {
- int h;
- struct node *tree=NULL;
- tree=build(tree);
- mid(tree);
- printf("\n");
- last(tree);
- printf("\n");
- leaf(tree);
- printf("%d\n",ans);
- h=dptree(tree);
- printf("%d\n", h);
- return 0;
- }