二叉树的建立与遍历
来源:互联网 发布:java方法覆盖 编辑:程序博客网 时间:2024/06/15 22:54
数据结构实验之二叉树的建立与遍历
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<iostream>#include<cstdio>#include<cstring>using namespace std;char head[200];int top,sum,deep;struct Tree{ char c; Tree* L,*R;};Tree* Creat(){ Tree* p; p=new Tree; p->L=NULL; p->R=NULL; return p;}Tree* Build(Tree*root){ if(!head[top]||head[top]==',') return NULL; root=Creat(); root->c=head[top]; top++; root->L=Build(root->L); top++; root->R=Build(root->R); return root;}int InOrder(Tree* root,int ans){ if(!root) { if(ans>deep) { deep=ans; } return 0; } if(!root->L&&!root->R) { sum++; } InOrder(root->L,ans+1); printf("%c",root->c); InOrder(root->R,ans+1);}int PostOrder(Tree* root){ if(!root) return 0; PostOrder(root->L); PostOrder(root->R); printf("%c",root->c);}int main(){ cin>>head; top=0; sum=0; deep=0; Tree* root=Build(root); InOrder(root,0); cout<<endl; PostOrder(root); cout<<endl; cout<<sum<<endl; cout<<deep<<endl;}
0 0
- 二叉树的建立与遍历
- c++二叉树的建立与遍历
- 二叉树的建立与先序中序后序遍历
- C++二叉树的建立与遍历
- 二叉树的建立与遍历
- 二叉树的遍历与建立
- 二叉树的建立与遍历
- 二叉树的建立与遍历
- 二叉树的建立与遍历
- 数据结构 二叉树的建立与遍历
- 二叉树的建立与遍历
- 二叉树的建立 与 遍历
- 二叉树的建立与遍历
- 二叉树的建立与遍历
- 二叉树的建立与遍历
- 线索二叉树的建立与遍历
- 二叉树的建立与遍历
- 二叉树的建立与遍历
- PHP 构造方法说明
- UIButton 导航栏属性
- c++中 dialog、bitmap等资源,由一个项目完全复制到另一个项目的方法
- HDU ACM 5265 pog loves szh II
- 【Oracle篇】Navicat连接Oracle数据库
- 二叉树的建立与遍历
- QImage 与 cv::Mat 之间的相互转换
- C++经典面试题(十)
- 实战黑帽seo从网站搭建到泛站快速排名
- storyboard
- 关于程序员学英语的经验
- Java基础 System类
- leetcode Basic Calculator II
- 西普CTF训练(programe部分分析)