您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树二:遍历二叉树

2017-10-26 17:26 197 查看
Problem Description

已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并按中序和后序的方式遍历该二叉树。

Input

连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。

Output

每组输入数据对应输出2行:

第1行输出中序遍历序列;

第2行输出后序遍历序列。

Example Input

abc,,de,g,,f,,,

Example Output

cbegdfa

cgefdba

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef char telemtype;
typedef struct Binode
{
telemtype data;
struct Binode *lchild,*rchild;
} Binode,*Bitree;
char s[55];
int i;
Bitree creat(Bitree &T)//先序建树
{
if(s[i++]==',')
return NULL;
else
{
T=new Binode;
T->data=s[i-1];
T->lchild=creat(T->lchild);
T->rchild=creat(T->rchild);
}
return T;
}
void found1(Bitree T)//中序遍历
{
if(T)//如果T不等于空。如果是空的,走下面的过程,一直空空空,所以程序停止
{
found1(T->lchild);
cout<<T->data;
found1(T->rchild);
}
}
void found2(Bitree T)//后序遍历
{
if(T)//错误点
{
found2(T->lchild);
found2(T->rchild);
cout<<T->data;
}
}
int main()
{
Bitree T;
while(cin>>s)
{
i=0;
T=creat(T);
found1(T);
cout<<endl;//忘记写了!
found2(T);
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: