数据结构实验之二叉树二:遍历二叉树
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并按中序和后序的方式遍历该二叉树。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
每组输入数据对应输出2行:
第1行输出中序遍历序列;
第2行输出后序遍历序列。
Sample Input
abc,,de,g,,f,,,
Sample Output
cbegdfa
cgefdba
Hint
Source
xam
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
struct node
{
char x;
node *l, *r;
};
int cnt = 0;
char s[110];
node * creat()
{
node *rt;
if(s[cnt++] == ',')
return NULL;
rt = new node();
rt->x = s[cnt-1];
rt->l = creat();
rt->r = creat();
return rt;
}
void ord(node *rt)
{
if(rt)
{
ord(rt->l);
printf("%c", rt->x);
ord(rt->r);
}
}
void la(node *rt)
{
if(rt)
{
la(rt->l);
la(rt->r);
printf("%c", rt->x);
}
}
int main()
{
while(~scanf("%s", s))
{
cnt = 0;
node *root = NULL;
root = creat();
ord(root);
printf("\n");
la(root);
printf("\n");
}
return 0;
}
本文介绍了一种根据先序遍历序列构建二叉树,并实现中序和后序遍历的方法。通过输入一个包含字符和空节点标识的字符串,算法能够重建二叉树结构,并输出其对应的中序和后序遍历序列。
296

被折叠的 条评论
为什么被折叠?



