从节点树中查找路径是一种常见的算法问题,可以通过深度优先搜索(DFS)或广度优先搜索(BFS)来解决。下面是两种常见的解决方法:
以下是一个使用深度优先搜索查找路径的示例代码:
def dfs(node, target, path, result):
if node is None:
return
path.append(node)
if node == target:
result.append(path.copy())
else:
for child in node.children:
dfs(child, target, path, result)
path.pop()
def find_path(root, target):
result = []
dfs(root, target, [], result)
return result
以下是一个使用广度优先搜索查找路径的示例代码:
from collections import deque
def bfs(root, target):
queue = deque([(root, [root])])
result = []
while queue:
node, path = queue.popleft()
if node == target:
result.append(path)
for child in node.children:
queue.append((child, path + [child]))
return result
def find_path(root, target):
return bfs(root, target)
以上是两种常见的从节点树中查找路径的方法。根据具体的应用场景和需求,选择适合的算法来解决问题。
领取专属 10元无门槛券
手把手带您无忧上云