数据结构实验之二叉树的建立与遍历
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知一个按先序序列输入的字符序列,如abc,,de,g,,f,,,(其中逗号表示空节点)。请建立二叉树并按中序和后序方式遍历二叉树,最后求出叶子节点个数和二叉树深度。
Input
输入一个长度小于50个字符的字符串。
Output
输出共有4行:
第1行输出中序遍历序列;
第2行输出后序遍历序列;
第3行输出叶子节点个数;
第4行输出二叉树深度。
Sample Input
abc,,de,g,,f,,,
Sample Output
cbegdfa cgefdba 3 5
题目链接:
http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/2711/pid/2136
#include <bits/stdc++.h>
using namespace std;
int top;
char str[51];
typedef struct treenode{
char s;
struct treenode *leftnode;
struct treenode *rightnode;
}node;
node *create()
{
top++;
node *root;
if(str[top]==',')
return NULL;
else
{
root=new node;
root->s=str[top];
root->leftnode=create();
root->rightnode=create();
}
return root;
}
void mid(node *root)
{
if(root)
{
mid(root->leftnode);
cout << root->s;
mid(root->rightnode);
}
}
void last(node *root)
{
if(root)
{
last(root->leftnode);
last(root->rightnode);
cout << root->s;
}
}
int leave(node *root)
{
if(!root)
return 0;
else if(!root->leftnode&&!root->rightnode)
return 1;
else
return leave(root->leftnode)+leave(root->rightnode);
}
int depth(node *root)
{
if(!root)
return 0;
else
return max(depth(root->leftnode),depth(root->rightnode))+1;
}
int main()
{
cin >> str;
top=-1;
node *root=create();
mid(root);
cout << endl;
last(root);
cout << endl;
cout << leave(root) << endl;
cout << depth(root) << endl;
return 0;
}