tree *data[1000];
int tou=0,wei=0;
void print(tree *p)
{
data[tou]=p;
wei++;
while(tou!=wei)
{
cout<<data[tou]->data;
if(data[tou]->left !=NULL)
{
data[wei]=data[tou]->left;
wei++;
}
if(data[tou]->right !=NULL)
{
data[wei]=data[tou]->right ;
wei++;
}
tou++;
}
}
这里用到队列的思想,从对头开始处理,将每一次往下的节点放入队尾,直到对头和队尾相等(队空)
完整代码:
#include<iostream>
using namespace std;
typedef struct Tree
{
char data;
struct Tree *left;
struct Tree *right;
}tree;
void creat(tree *&p)
{
char x;
cin>>x;
if(x!='#')
{
p=new tree;
p->data =x;p->left =NULL;p->right =NULL;
creat(p->left );
creat(p->right );
}
}
tree *data[1000];
int tou=0,wei=0;
void print(tree *p)
{
data[wei]=p;
wei++;
while(tou!=wei)
{
cout<<data[tou]->data;
if(data[tou]->left !=NULL)
{
data[wei]=data[tou]->left;
wei++;
}
if(data[tou]->right !=NULL)
{
data[wei]=data[tou]->right ;
wei++;
}
tou++;
}
}
int main()
{
tree *p=NULL;
creat(p);
print(p);
return 0;
}