Skip to content

Problem 3.1: Cumulative Mul (100pts)

Problem

Write a function cumulative_mul that mutates the Tree t so that each node's label becomes the product of all labels in the subtree rooted at the node.

编写一个函数 cumulative_mul,它修改t,使得每个节点的标签变为以该节点为子树中所有标签的乘积

def cumulative_mul(t):
    """Mutates t so that each node's label becomes the product of all labels in
    the corresponding subtree rooted at t.

    >>> t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)])
    >>> cumulative_mul(t)
    >>> t
    Tree(105, [Tree(15, [Tree(5)]), Tree(7)])
    """
    "*** YOUR CODE HERE ***"

Hints

Hint1: The answer is simple and neat. If your answer is too complicated, you might want to review Section 2.3 and compare the difference between the oop-style Tree and the functional-style tree.

Hint2: The label of a tree might not be an integer since operator * can be overloaded just as you've done before.

  • 答案应该简单而简洁。如果你的答案过于复杂,你可能需要回顾 第 2.3 节,并比较 面向对象风格Tree函数式风格tree 之间的区别。

  • 树的标签可能不是一个整数,因为运算符 * 可以被重载,就像你以前做过的那样。