Python 对于这个与树相关的问题,我应该怎么做?

Python 对于这个与树相关的问题,我应该怎么做?,python,tree,Python,Tree,问题是:定义一个函数sprout_leaves,它接受树t和值列表vals。它生成一个与t相同的新树,但每个旧叶节点都有新的分支,VAL中的每个值对应一个分支 def sprout_leaves(t, vals): """Sprout new leaves containing the data in vals at each leaf in the original tree t and return the resulting tree. >>>

问题是:定义一个函数sprout_leaves,它接受树t和值列表vals。它生成一个与t相同的新树,但每个旧叶节点都有新的分支,VAL中的每个值对应一个分支

def sprout_leaves(t, vals):
    """Sprout new leaves containing the data in vals at each leaf in
    the original tree t and return the resulting tree.

    >>> t1 = tree(1, [tree(2), tree(3)])
    >>> print_tree(t1)
    1
      2
      3
    >>> new1 = sprout_leaves(t1, [4, 5])
    >>> print_tree(new1)
    1
      2
        4
        5
      3
        4
        5

    >>> t2 = tree(1, [tree(2, [tree(3)])])
    >>> print_tree(t2)
    1
      2
        3
    >>> new2 = sprout_leaves(t2, [6, 1, 2])
    >>> print_tree(new2)
    1
      2
        3
          6
          1
          2
    """

def tree(label, branches=[]):
    """Construct a tree with the given label value and a list of branches."""
    for branch in branches:
        assert is_tree(branch), 'branches must be trees'
    return [label] + list(branches)

def label(tree):
    """Return the label value of a tree."""
    return tree[0]

def branches(tree):
    """Return the list of branches of the given tree."""
    return tree[1:]

def is_tree(tree):
    """Returns True if the given tree is a tree, and False otherwise."""
    if type(tree) != list or len(tree) < 1:
        return False
    for branch in branches(tree):
        if not is_tree(branch):
            return False
    return True

def is_leaf(tree):
    """Returns True if the given tree's list of branches is empty, and False
    otherwise.
    """
    return not branches(tree)


我在用修改过的树枝替换原来的树枝时遇到了麻烦。 例如,如果原始树是[1,[2,3]],而修改的分支是[2,[4,5],3,[4,5]],我应该如何重新设置[2,[4,5],3,[4,5]]? 任何帮助都将不胜感激

What I've tried so far is:
def sprout_leaves(t, vals):
    if is_leaf(t):
        t += [vals]
    else:
        new_branches = []
        for branch in branches(t):
            if is_leaf(label(branch)):
                for j in range(0, len(label(branch))):
                    [label(branch)[j]] += [vals]
                    new_branches += [label(branch)[j]]
            **????**
    return t