按层遍历二叉树是广度优先的算法,这个算法需要一个队列,最开始将根节点入队,然后处理队列,直到队列为空,这样就处理完了整棵树。
好吧,看起来广度优先遍历是这么的简单,与深度优先不同,广度优先使用队列,见下面的代码。处理一个节点时,如果该节点有左儿子将左儿子入队,如果有右儿子将右儿子入队,这样就会按距离遍历完所有的节点。
#include <iostream>
#include <string>
#include <queue>
using namespace std;
struct tree {
int value;
struct tree *lchild;
struct tree *rchild;
};
struct tree *insert(struct tree *root, int value)
{
if (root) {
if (value < root->value) {
root->lchild = insert(root->lchild, value);
} else {
root->rchild = insert(root->rchild, value);
}
} else {
root = new struct tree;
root->value = value;
root->lchild = 0;
root->rchild = 0;
}
return root;
}
void print(struct tree *root)
{
queue<struct tree *> list;
list.push(root);
cout << "list:";
while (!list.empty()) {
struct tree *node = list.front();
if (node->lchild)
list.push(node->lchild);
if (node->rchild)
list.push(node->rchild);
list.pop();
cout << " " << node->value;
}
cout << endl;
}
int main()
{
struct tree *root = 0;
root = insert(root, 100);
root = insert(root, 233);
root = insert(root, 33);
root = insert(root, 67);
root = insert(root, 104);
root = insert(root, 34);
root = insert(root, 32);
root = insert(root, 766);
root = insert(root, 456);
print(root);
return 0;
}