ami*_*mit 14
级别顺序遍历实际上是一个BFS,它本质上不是递归的.它使用Queue而不是Stack来保存应该打开的下一个顶点.其原因在于此遍历,您希望以FIFO顺序打开节点,而不是通过递归获得的LIFO顺序
正如我所提到的,级别顺序实际上是BFS,其[BFS]伪代码[取自维基百科]是:
1 procedure BFS(Graph,source):
2 create a queue Q
3 enqueue source onto Q
4 mark source
5 while Q is not empty:
6 dequeue an item from Q into v
7 for each edge e incident on v in Graph:
8 let w be the other end of e
9 if w is not marked:
10 mark w
11 enqueue w onto Q
Run Code Online (Sandbox Code Playgroud)
(*)在树中,不需要标记顶点,因为您无法到达2个不同路径中的同一节点.
小智 5
void levelorder(Node *n)
{ queue < Node * >q;
q.push(n);
while(!q.empty())
{
Node *node = q.front();
cout<<node->value;
q.pop();
if(node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
}
}
Run Code Online (Sandbox Code Playgroud)