#include <iostream>
#include <cstring>
#include <algorithm>
#define maxn 1005
#include <map>
#include <queue>
using namespace std;
class node
{
public:
node(char c,node*l=NULL,node*r=NULL):c(c),l(l),r(r){};
node *l,*r;
char c;
};
int num=-1;
void build(char *s,node *& root)
{
num++;
if(num>strlen(s))return;
if(root==NULL)
{
if(s[num]=='#')return;
else root=new node(s[num]);
}
build(s,root->l);
build(s,root->r);
}
void preorder(node*root)
{
if(root!=NULL)
{
cout<<root->c;
}
else return;
preorder(root->l);
preorder(root->r);
}
void levelorder(node *root)
{
int level=0;
map<node*,int>mp;
queue<node*>q;
q.push(root);
mp[root]=1;
node * tmp=NULL;
while(!q.empty())
{
tmp=q.front();
q.pop();
if(mp[tmp]>level)
{
level=mp[tmp];
cout<<endl<<tmp->c;
}
else cout<<tmp->c;
if(tmp->l!=NULL)
{
mp[tmp->l]=mp[tmp]+1;
q.push(tmp->l);
}
if(tmp->r!=NULL)
{
mp[tmp->r]=mp[tmp]+1;
q.push(tmp->r);
}
}
}
void destroy(node * &root)
{
if(root->l==NULL&&root->r==NULL)
{
delete root;
root=NULL;
return;
}
destroy(root->l);
destroy(root->r);
}
int main()
{
char s[maxn];
node * root=NULL;
while(cin>>s)
{
num=-1;
build(s,root);
//preorder(root);
levelorder(root);
//destroy(root);
}
}
先根递归建立二叉树(顺序表示法)
最新推荐文章于 2024-12-15 20:54:13 发布