经典算法之层序遍历二叉树

参考:https://blog.csdn.net/wardseptember/article/details/78879360

要进行层序遍历,需要建立一个循环队列。先将二叉树头结点入队列,然后出队列,访问该结点,

如果它有左子树,则将左子树的根结点入队;

如果它有右子树,则将右子树的根结点入队。

然后出队列,对出队结点访问,如此反复,直到队列为空为止。

#include <iostream>
#include <vector>
#include <deque>

using namespace std;


typedef struct BTNode {
	char val;
	struct BTNode *left, *right;
	BTNode(char x) :
		val(x), left(nullptr), right(nullptr) {
	}
}BTNode, *BTree;

//创建一棵二叉树
BTree createTree() {
	BTree pA = new BTNode('A');
	BTree pB = new BTNode('B');
	BTree pC = new BTNode('C');
	BTree pD = new BTNode('D');
	BTree pE = new BTNode('E');
	BTree pF = new BTNode('F');
	BTree pG = new BTNode('G');
	BTree pH = new BTNode('H');
	BTree pI = new BTNode('I');

	pA->left = pC;
	pA->right = pB;
	pC->left = pD;
	pC->right = pE;
	pB->right = pF;
	pD->left = pG;
	pE->right = pH;
	pF->left = pI;

	return pA;
}

void levelOrderBTree(BTree pT) {
	if (pT != nullptr) {
		deque<BTNode *> que;
		que.push_back(pT);
		BTNode *q;

		while (!que.empty()) {
			q = que.front();
			que.pop_front();
			//打印节点,也可以执行其他操作
			cout << q->val;

			if (q->left != nullptr) {
				que.push_back(q->left);
			}
			if (q->right != nullptr) {
				que.push_back(q->right);
			}
		}
	}
}

int main() {
	BTree pTree = createTree();

	cout << "层序遍历:";
	levelOrderBTree(pTree);
	cout << endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值