数据结构实验之二叉树的建立与遍历
2016-04-12 22:59
381 查看
数据结构实验之二叉树的建立与遍历
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。输入
输入一个长度小于50个字符的字符串。输出
输出共有4行:第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
示例输入
abc,,de,g,,f,,,
示例输出
cbegdfacgefdba35
提示
#include <stdio.h> #include <stdlib.h> #include <string.h> struct node { char data; struct node *l, *r; }; int cnt; char s[100]; int max(int x, int y) { if(x > y){ return x; }else { return y; } } struct node *creat() { cnt++; struct node *q; if(s[cnt]==','){ q = NULL; }else { q = (struct node *)malloc(sizeof(struct node)); q->data = s[cnt]; q->l = creat(); q->r = creat(); } return q; } void two(struct node *tree) { if(tree){ two(tree->l); printf("%c", tree->data); two(tree->r); } } void three(struct node *tree) { if(tree){ three(tree->l); three(tree->r); printf("%c", tree->data); } } int Nnode(struct node *tree) { int digit; if(tree==NULL){ digit = 0; }else if(tree->l==NULL&&tree->r==NULL){ digit = 1; }else { digit = Nnode(tree->l) + Nnode(tree->r); } return digit; } int deep(struct node *tree) { int x, y; if(tree!=NULL){ x = deep(tree->l); y = deep(tree->r); return max(x,y)+1; }else { return 0; } } int main() { struct node *tree; while(~scanf("%s",s)){ cnt = -1; tree = creat(); two(tree); printf("\n"); three(tree); printf("\n"); printf("%d\n", Nnode(tree)); printf("%d\n", deep(tree)); } return 0; }
相关文章推荐
- Nim Game
- 【数据结构与算法】String大数加减乘除(非负整数)
- 【数据结构】 出栈序列的合法性【面试】
- 通讯录——数据结构课设
- 数据结构-栈的实现之数制转换
- 数据结构和算法03 之链表
- BZOJ 1588 Treap模版题
- 【方法论】从入门到精通是怎样一种体验
- 数据结构之循环链表
- 数据结构的基本概念
- 数据结构(10):二叉树基本功能的实现
- java数据结构和算法目录(持续更新中)
- YTUOJ之判断是否是子串(串)
- 基于二叉查找树的符号表
- 数据结构之链表
- OpenCascade中网格的数据结构
- 第二章 基本数据结构和运算
- C++ 常用容器or数据结构
- 数据结构实验1 线性表的有关操作
- 【数据结构】Stack 栈(更新时间:2016-04-13)