源代码:
#include <iostream>
#include <cstdlib>
#include <queue>
using namespace std;
typedef struct Node {
char root;
struct Node *lchild;
struct Node *rchild;
} *Tree;
//广度优先遍历
void breadthFirstSearch(Tree root)
{
if (!root)
{
return;
}
queue<Node *> nodeQueue;
nodeQueue.push(root);
Node *node;
while(!nodeQueue.empty())
{
node = nodeQueue.front();
nodeQueue.pop();
cout << node->root << " ";
if(node->lchild)
{
nodeQueue.push(node->lchild); //先将左子树入队
}
if(node->rchild)
{
nodeQueue.push(node->rchild); //再将右子树入队
}
}
}
//创建二叉树
void CreateBtree(Tree * T)
{
char ch;
cout << "请输入字符:(输入#表示为空!)" << endl;
cin >> ch;
if (ch == '#')
{
*T = NULL;
}
else
{
*T = (Tree)malloc(sizeof(Node));
(*T)->root = ch;
CreateBtree(&(*T)->lchild);
CreateBtree(&(*T)->rchild);
}
}
void releasetree(Tree T)
{
if (T)
{
releasetree(T->lchild);
releasetree(T->rchild);
free(T);
T == NULL;
}
}
int main()
{
Tree T;
CreateBtree(&T);
breadthFirstSearch(T);
releasetree(T);
return 0;
}
运行结果截图: