把图的深度优先遍历、广度优先遍历改为输出深度优先生成树、广度优先生成树代码
时间: 2023-12-25 18:04:56 浏览: 116
深度优先生成树(DFS生成树)的代码:
```python
def dfs_tree(graph, start):
visited = set()
tree = {}
def dfs(node, parent=None):
visited.add(node)
if parent:
if parent not in tree:
tree[parent] = []
tree[parent].append(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs(neighbor, node)
dfs(start)
return tree
```
广度优先生成树(BFS生成树)的代码:
```python
from collections import deque
def bfs_tree(graph, start):
visited = set()
tree = {}
queue = deque([(start, None)])
while queue:
node, parent = queue.popleft()
visited.add(node)
if parent:
if parent not in tree:
tree[parent] = []
tree[parent].append(node)
for neighbor in graph[node]:
if neighbor not in visited:
queue.append((neighbor, node))
visited.add(neighbor)
return tree
```
其中,`graph` 是图的邻接表表示,`start` 是遍历起点。生成树的结果以字典形式返回,其中键是父节点,值是其直接子节点列表。
阅读全文