二叉树广度优先遍历

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;

struct Node
{
char data;
Node *LT;
Node *RT;
};

class BTree
{
public:
Node * root;
public:
BTree()
{
root=new Node();
char d;
cout<<"please input data of root\n";
cin>>d;
root->data=d;
root->LT=NULL;
root->RT=NULL;
}
void buildTree2()
{
Node *temp1,*temp2;
temp1=new Node();
temp2=new Node();

temp1->data ='5';
temp1->LT=NULL;
temp1->RT =NULL;
root->LT=temp1;

temp2->data ='7';
temp2->LT=NULL;
temp2->RT =NULL;
root->RT =temp2;
}
};
void preOrder(Node *root)//前序遍历
{
if (root!=NULL)
{
cout<<root->data<<endl;
preOrder(root->LT);
preOrder(root->RT);
}
return;
}
void midOrder(Node *root)//中序遍历
{
if(root!=NULL)
{
midOrder(root->LT);
cout<<root->data<<endl;
midOrder(root->RT);

}
return;
}
void postOrder(Node *root)//后序遍历
{
if(root!=NULL)
{
postOrder(root->LT);
postOrder(root->RT);
cout<<root->data<<endl;

}
return;
}

void main()
{
BTree bt;
bt.buildTree2();
cout<<"preorder\n";
preOrder(bt.root);
cout<<"midOrder"<<endl;
midOrder(bt.root);
cout<<"postOrder"<<endl;
postOrder(bt.root);

}
再增加一个广度优先遍历,我想知道怎么在建立一个可以存结点的数组队列

第1个回答  推荐于2016-12-01
#include<queue>
void bfs(Node*root)
{

queue<Node*> q;
Node* p;

if(root!=NULL)
{
q.push(root);
}
else return;
while(!q.empty())
{
p=q.front();

if(p->LT) q.push(p->LT);
if(p->RT) q.push(p->RT);
cout<<p->data<<endl;
q.pop();

}

}本回答被提问者采纳