二叉树的层次遍历也是在面试中经常考到的一个内容。我们看看下面这个二叉树的层次遍历:
层次遍历不同于前序、中序和后序遍历。它是一层一层的来访问树的结点。
对于层次遍历,我们可以利用队列这种数据结构。具体的操作看代码。
上面这颗二叉树的层次遍历结果应该是: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);
}
}