找到树中最长的路径

时间:2017-12-08 06:48:03

标签: python-3.x tree

class Tree:
def __init__(self, root, subtrees) -> None:
    """Initialize a new Tree with the given
    root value and subtrees.

    If <root> is None, the tree is empty.
    Precondition:
    - if <root> is None,
      then <subtrees> is empty.
    """
    self._root = root
    self._subtrees = subtrees

def long(self):
  """Return a list of items on the longest possible path 
  between the root of this tree and one of its leaves.

  If there is more than one path with the maximum length, 
  return the one that ends at the leaf that is furthest to the left.

  If this tree is empty, return an empty list.

  @type self: Tree 
  @rtype: list 
  """
  if len([s 
  for s in self._subtrees
  if s is not None]) == 0:
    return []
  else:
    return [self._root] + [s.long() for s in self._subtrees]

我试图找到树中从根到叶的最长路径。我的代码没有递归到树的结尾并返回一堆空列表。请帮忙。

0 个答案:

没有答案