友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
Breadth First Search 广度优先搜索
Tree Breadth First Search,树上的BFS
这种模式基于宽搜(Breadth First Search (BFS)),适用于需要遍历一颗树。借助于队列数据结构,从而能保证树的节点按照他们的层数打印出来。打印完当前层所有元素,才能执行到下一层。所有这种需要遍历树且需要一层一层遍历的问题,都能用这种模式高效解决。
这种树上的BFS模式是通过把根节点加到队列中,然后不断遍历直到队列为空。每一次循环中,我们都会把队头结点拿出来(remove),然后对其进行必要的操作。在删除每个节点的同时,其孩子节点,都会被加到队列中。
识别树上的BFS模式:
-
如果你被问到去遍历树,需要按层操作的方式(也称作层序遍历)
经典题目
-
[0323-number-of-connected-components-in-an-undirected-graph]
-
[1284-minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix]
-
[1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid]
-
[1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree]
-
[1430-check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree]
-
[1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero]
-
[1625-lexicographically-smallest-string-after-applying-operations]
-
[2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph]
-
[2471-minimum-number-of-operations-to-sort-a-binary-tree-by-level]
-
[2556-disconnect-path-in-a-binary-matrix-by-at-most-one-flip]
-
[2814-minimum-time-takes-to-reach-destination-without-drowning]
-
[3372-maximize-the-number-of-target-nodes-after-connecting-trees-i]
-
[3373-maximize-the-number-of-target-nodes-after-connecting-trees-ii]