按层遍历二叉树

按层遍历二叉树是广度优先的算法,这个算法需要一个队列,最开始将根节点入队,然后处理队列,直到队列为空,这样就处理完了整棵树。

好吧,看起来广度优先遍历是这么的简单,与深度优先不同,广度优先使用队列,见下面的代码。处理一个节点时,如果该节点有左儿子将左儿子入队,如果有右儿子将右儿子入队,这样就会按距离遍历完所有的节点。

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值