数据结构实验之二叉树二:遍历二叉树
Description
已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并按中序和后序的方式遍历该二叉树。
Input
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output
每组输入数据对应输出2行:
第1行输出中序遍历序列;
第2行输出后序遍历序列。
Sample
Input
abc,,de,g,,f,,,
Output
cbegdfa
cgefdba
Hint
代码:
#include<bits/stdc++.h>
using namespace std;
typedef struct Tnode
{
char data;
struct Tnode *lchild;
struct Tnode *rchild;
}Tnode, *Tlink;
char s[55];
int l;
int sum;
Tlink createtree(struct Tnode *root)
{
if(sum == l) return NULL;
char c = s[sum++];
if(c == ',') return NULL;
if(root == NULL)
{
root = new Tnode;
root -> data = c;
root -> lchild = NULL;
root -> rchild = NULL;
}
root -> lchild = createtree(root -> lchild);
root -> rchild = createtree(root -> rchild);
return root;
}
void inorder(Tlink root)
{
if(root == NULL)
{
return ;
}
else
{
inorder(root->lchild);
cout << root -> data;
inorder(root->rchild);
}
}
void postorder(Tlink root)
{
if(root == NULL)
{
return ;
}
else
{
postorder(root->lchild);
postorder(root->rchild);
cout << root -> data;
}
}
int main()
{
while(~scanf("%s",s))
{
l = strlen(s);
sum = 0;
Tlink root = NULL;
root = createtree(root);
inorder(root);
cout<< endl;
postorder(root);
cout << endl;
}
return 0;
}