7-5 建立与遍历二叉树
以字符串的形式定义一棵二叉树的先序序列,若字符是‘#’,
表示该二叉树是空树,否则该字符是相应结点的数据元素。读入相应先序序列,建立二叉链式存储结构的二叉树,然后中序遍历该二叉树并输出结点数据。
输入格式: 字符串形式的先序序列(即结点的数据类型为单个字符)
输出格式: 中序遍历结果
输入样例: 在这里给出一组输入。例如:
ABC##DE#G##F###
输出样例: 在这里给出相应的输出。
例如:CBEGDFA
#include<iostream>
using namespace std;
class Tree{
char data;
Tree *Leftchild;
Tree *Rightchild;
public:
Tree()
{
data='#';
}
void CreatTree()
{
char a;
cin>>a;
if(a=='#')
{
Leftchild=NULL;
Rightchild=NULL;
return;
}
data=a;
Leftchild=new Tree;
Leftchild->CreatTree();
Rightchild=new Tree;
Rightchild->CreatTree();
}
void PreorderTree()
{
if(data=='#')
return;
Leftchild->PreorderTree();
cout<<data;
Rightchild->PreorderTree();
}
};
int main()
{
Tree *t=new Tree;
t->CreatTree();
t->PreorderTree();
return 0;
}
~~~c