题目描述
编一个程序,读入先序遍历字符串,根据此字符串建立一棵二叉树(以指针方式存储)。
例如如下的先序遍历字符串:
A ST C # # D 10 # G # # F # # #
各结点数据(长度不超过3),用空格分开,其中“#”代表空树。
建立起此二叉树以后,再按要求输出二叉树。
输入
输入由多组测试数据组成。
每组数据包含一行字符串,即二叉树的先序遍历,字符串长度大于0且不超过100。
输出
对于每组数据,显示对应的二叉树,然后再输出一空行。输出形式相当于常规树形左旋90度。见样例。 注意二叉树的每一层缩进为4,每一行行尾没有空格符号。
样例输入 Copy
A ST C # # D 10 # G # # F # # # 4 2 1 # # 3 # # 5 # 6 # #
样例输出 Copy
A F D G 10 ST C 6 5 4 3 2 1
#include<iostream>
#include<cstdio>
#include<cstring>
#include<math.h>
using namespace std;
int sum=0;int flag=0;//sum记录当前层数,判断空格的输入,flag判断输入是否结束,跳出循环
typedef struct node{
string s;
struct node *lchild;
struct node *rchild;
}node,*Node;
void Creatnode(Node &p){//建立节点
p=new node;
cin>>p->s;
if(p->s[0]=='#');
else {
Creatnode(p->lchild);
Creatnode(p->rchild);}
}
int CreatTree(Node &Tree){//建立树
Tree=new node;
cin>>Tree->s;
if(!(Tree->s[0])){flag=1;return 0;
}
Creatnode(Tree->lchild);
Creatnode(Tree->rchild);
return 1;
}
void Outnode(Node p){//输出节点
sum++;
if(p->s[0]=='#');
else {
Outnode(p->rchild);
for(int i=0;i<sum;i++)printf(" ");
cout<<p->s<<endl;
Outnode(p->lchild);}
sum--;
}
void OutTree(Node Tree){//输出树
Outnode(Tree->rchild);
cout<<Tree->s<<endl;
Outnode(Tree->lchild);
}
int main(){
while(1){
Node Tree;
CreatTree(Tree);
if(flag==1)break;
OutTree(Tree);
cout<<endl;
}
return 0;
}