python - 如何调整 DFS 以遍历具有非唯一节点标识符的 m-ary 树?
问题描述
我需要在不同节点具有相同标识符的 m-ary 树上运行 DFS。此外,我需要访问所有节点,而不是树的去重版本。
假设我定义我的 m-ary 树(为简单起见这里是二进制)如下:
# the branch with parent node 2 appears twice in the tree
tree = {1: {2, 3}, 2: {4, 5}, 3: {2, 6}}
print(tree)
我通常会按如下方式实现 DFS,即考虑访问节点:
# initialize stack with root node
stack = [1]
visited = set()
# record the order
dfs = []
while stack:
current = stack.pop()
dfs.append(current)
if current not in visited:
visited.add(current)
if current in tree:
stack.extend(tree[current])
else:
# we have a leaf node
pass
print(dfs)
这会产生以下正确但不是我想要的顺序,因为它将忽略父 2 的第二个分支出现:
[1, 3, 6, 2, 5, 4]
我可以改为忽略visited
逻辑并直接执行:
# initialize stack with root node
stack = [1]
# record the order
dfs = []
while stack:
current = stack.pop()
dfs.append(current)
if current in tree:
stack.extend(tree[current])
else:
# we have a leaf node
pass
print(dfs)
这会产生所需的以下顺序:
[1, 3, 6, 2, 5, 4, 2, 5, 4]
当我摆脱已访问的支票时,是否有我遗漏的边境案例?
解决方案
推荐阅读
- python - 如何中断否则超时的线程?
- android - 打开另一个活动有多安全?
- autocomplete - Ant Design React - 如何打开多种自动完成模式
- python - 为什么我不能通过更多进程获得并行化优势?
- android - 无法从 android_assets 访问张量模型
- html - 从单个页面中删除导航
- expression - 基于框架的动态笔画宽度的 PaintCode 表达式
- mongodb - 从后端到前端的文件传输最有效的解决方案是什么
- javascript - 触发焦点,然后触发 mousedown 事件
- java - 我在java编程中遇到问题。我收到一个错误“列计数与第 1 行的值计数不匹配”