数据结构实验之二叉树的建立与遍历
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。
输入
输入一个长度小于50个字符的字符串。
输出
输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
示例输入
abc,,de,g,,f,,,
示例输出
cbegdf
acgefdba
3
5
二叉树。。。不多说了
//二叉树的建立与遍历 #include <iostream> #include <string> #include <cstdio> using namespace std; typedef struct node { char data; node *left,*right; }Bn,*Bt; void ctree(Bt &T) //先序建立二叉树 { char c; cin>>c; if(c==',') T=NULL; else { T=new Bn; T->data=c; ctree(T->left); ctree(T->right); } } void first(Bt T)//先序遍历 { if(T) { cout<<T->data; first(T->left); first(T->right); } } void in(Bt T)//中序遍历 { if(T) { in(T->left); cout<<T->data; in(T->right); } } void last(Bt T) //后序遍历 { if(T) { last(T->left); last(T->right); cout<<(T->data); } } int count=0; void calleaf(Bt T) //计算叶子节点数 { if(T) { if(!T->left&&!T->right) { count++; return ; } calleaf(T->left); calleaf(T->right); } } int deep(Bt T) //计算深度 { int dep=0; if(!T) return dep; int nleft=deep(T->left); int nright=deep(T->right); return (nleft>nright?nleft:nright)+1; } int main() { Bt root; ctree(root); first(root); cout<<endl; in(root); cout<<endl; last(root); cout<<endl; calleaf(root); cout<<count<<endl; cout<<deep(root)<<endl; return 0; }