#include "iostream"
#include "queue"
using namespace std;
struct Node
{
int data;
struct Node *lchild;
struct Node *rchild;
};
Node* CreateNode();
void BFS(Node *node);//层次遍历,也叫广度优先搜索遍历
void Xianxu(Node *node);//先序遍历
void Zhongxu(Node *node);//中序遍历
void Houxu(Node *node);//后序遍历
int main()
{
cout << "从键盘输入创建二叉树,输入-1表示该左子树或右子树为空"<<endl;
Node *node = CreateNode();//从键盘输入创建二叉树,输入-1表示该左子树或右子树为空
cout << "广度优先搜索的序列是" << endl;
BFS(node);
cout << endl;
cout << "先序序列是" << endl;
Xianxu(node);
cout << endl;
cout << "中序序列是" << endl;
Zhongxu(node);
cout << endl;
cout << "后序序列是" << endl;
Houxu(node);
system("pause");
return 0;
}
//递归建立二叉树
Node* CreateNode()
{
Node *node=new Node();
//Node *node
int d;
cin >> d;
if (d == -1)
{
node = NULL;
}
else
{
node->data = d;
node->lchild = CreateNode();
node->rchild = CreateNode();
}
return node;
}
//广度优先搜索
void BFS(Node *node)
{
queue<Node *> nodeQueue;
nodeQueue.push(node);
while (!nodeQueue.empty())
{
Node *tnode;
tnode = nodeQueue.front();
nodeQueue.pop();
cout << tnode->data << " ";
if(tnode->lchild!=NULL)
nodeQueue.push(tnode->lchild);
if (tnode->rchild != NULL)
nodeQueue.push(tnode->rchild);
}
}
void Xianxu(Node *node)
{
if (node != NULL)
{
cout << node->data << " ";
Xianxu(node->lchild);
Xianxu(node->rchild);
}
}
void Zhongxu(Node *node)
{
if (node != NULL)
{
Zhongxu(node->lchild);
cout << node->data << " ";
Zhongxu(node->rchild);
}
}
void Houxu(Node *node)
{
if (node != NULL)
{
Houxu(node->lchild);
Houxu(node->rchild);
cout << node->data << " ";
}
}