BFS and DFS

BFS 和 DFS 為用以在 tree 中搜尋特定 node 的演算法

  • Breadth-First Search 廣度優先搜尋
  • Depth-First Search 深度優先搜尋

相關文章:Binary Tree 二元樹

 

Iterative Implementation

BFS:使用 Queue

Template

queue = collections.deque([root])
while queue: 
  curr = queue.popleft() 
  # ... some process about target

  for child in ... : # [curr.left, curr.right]: 
    if child: 
      queue.append(child)

DFS:使用 Stack

Template

stack = [root]
while stack:
  curr = stack.pop()
  # ... some process about target
      
  for child in ... : # [curr.left, curr.right]:
    if child:
      stack.append(child)

Recursive Implementation

BFS

⭕️ DFS

Template

def recursive_dfs(curr, target):
  if curr is None:  
    return
        
  # ...
  for child in [curr.left, curr.right]:
    # ...
    subresult = recursive_dfs(child) 
    # ...

相關例題

相關例題

BFS

DFS

Last Updated on 2023/09/12 by A1go

目錄
Bitnami