级别顺序遍历实际上是BFS,它本质上不是递归的。它使用队列而不是堆栈来保存应打开的下一个顶点。发生这种情况的原因是,您希望以FIFO顺序而不是通过递归获得的LIFO顺序打开节点
正如我提到的,级别顺序实际上是一个BFS,其[BFS]伪代码[取自维基百科]为:
1 procedure BFS(Graph,source):2 create a queue Q3 enqueue source onto Q4 mark source5 while Q is not empty:6 dequeue an item from Q into v7 for each edge e incident on v in Graph:8 let w be the other end of e9 if w is not marked:10 mark w11 enqueue w onto Q
(*)在树中,不需要标记顶点,因为您无法通过2条不同的路径到达同一节点。



