如何查找给定树上是否存在路径?

时间:2019-06-08 14:37:20

标签: python tree

我想实现类似以下的功能:

def is_path(t, path):
    """Return whether a given path exists in a tree, beginning
    at the root.
    >>> t = tree(1, [
             tree(2, [tree(4), tree(5)]),
             tree(3, [tree(6), tree(7)])
          ])
    >>> is_path(t, [1, 2])
    True
    >>> is_path(t, [1, 2, 4])
    True
    >>> is_path(t, [2, 4])
    False
    """
    if _______________________________:
    return False
    if _______________________________:
        return True
    return any([____________________________________________________________])

助手功能:

label(tree)->树值

分支机构(树)->分支机构(也包括树)列表

例如

    1
   / \
  2   3

label(t)-> 1

分支机构(t)-> [tree(2),tree(3)]

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

要使该路径存在,在每次递归调用时,头节点必须等于路径列表中的第一个元素。如果不是,则树中没有匹配项。如果头节点确实等于列表中的第一个元素,并且输入列表的长度为1,则发现完全匹配。在每次调用的路径列表的长度为> 1时,必须在每个分支上调用该函数:

def is_path(t, path):
  if t.head != path[0]:
     return False
  if t.head == path[0] and len(path) == 1:
     return True
  return any(is_path(i, path[1:]) for i in t.children)

class tree:
  def __init__(self, _head, _children=[]):
    self.head, self.children = _head, _children

t = tree(1, [tree(2, [tree(4), tree(5)]), tree(3, [tree(6), tree(7)])])
print(is_path(t, [1, 2]))
print(is_path(t, [1, 2, 4]))
print(is_path(t, [2, 4]))
print(is_path(t, [1, 3, 7]))

输出:

True
True
False
True