测试输入:123##4##5##
输出:1
2 5
3 4
#include<iostream>
#include<vector>
using namespace std;
struct Node{
Node *rchild;
Node *lchild;
char data;
};
vector <Node*> edge;
Node *create(Node *bt)
{
char c;
cin>>c;
if(c=='#')
bt =NULL;
else{
bt =new Node;
bt->data=c;
bt->lchild=create(bt->lchild);
bt->rchild=create(bt->rchild);
}
return bt;
}
void levelorder(Node *bt){
if(bt==NULL)
return ;
int cur=0;
int last=1;//用来存储最后一个位置
edge.push_back(bt);
while(cur<edge.size()){
last=edge.size();
while(cur<last){
cout <<edge[cur]->data<<" ";
if(edge[cur]->lchild!=NULL)
{
edge.push_back(edge[cur]->lchild);
}
if(edge[cur]->rchild!=NULL)
{
edge.push_back(edge[cur]->rchild);
}
cur++;
}
cout <<endl; //cur等于last时候,访问结束,换行输入下一层
}
}
int main()
{
Node *bt;
bt=create(bt);
levelorder(bt);
return 0;
}