所有人看了都说好的二叉树的层次遍历

二叉树的层次遍历也是在面试中经常考到的一个内容。我们看看下面这个二叉树的层次遍历:

层次遍历不同于前序、中序和后序遍历。它是一层一层的来访问树的结点。

对于层次遍历,我们可以利用队列这种数据结构。具体的操作看代码。

上面这颗二叉树的层次遍历结果应该是:0  1 2 3 4 5 6 7 8 9.

接下来看下二叉树层次遍历的非递归的代码:

typedef struct Node
{
	int value;
	Node* lChild;
	Node* rChild;
}*BinaryTree;
void Arrangement(BinaryTree tree)
{
	queue<Node*> que;
	if (tree == nullptr)
		return;
	que.push(tree);
	Node* temp = nullptr;
	while (!que.empty())
	{
		temp = que.front();
		cout << temp->value << ends;
		que.pop();
		if (temp->lChild)
			que.push(temp->lChild);
		if (temp->rChild)
			que.push(temp->rChild);
	}
}
发布了124 篇原创文章 · 获赞 24 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42214953/article/details/104861521