Skip to content

Problem 3.1: Equal Trees (100 pts)

Problem

Recall that when Python evaluates the expression a + b, it is in fact evaluating a.__add__(b). Similarly, when Python evaluates the expression a == b, it is in fact evaluating a.__eq__(b).

Implement special method __eq__ in class Tree, such that we can simply use t1 == t2 to judge whether two trees t1 and t2 are equivalent trees (i.e. have equivalent labels and equivalent branches, and all of their branches are in the same order.).

回想一下,当 Python 评估表达式 a + b 时,它实际上是在评估 a.__add__(b)。类似地,当 Python 评估表达式 a == b 时,它实际上是在评估 a.__eq__(b)

在类 Tree 中实现特殊方法 __eq__,使得我们可以使用 t1 == t2 来判断两个树 t1t2 是否是等价的树(即具有等价的标签和等价的分支,并且所有分支的顺序相同)。

class Tree:
    ...

    def __eq__(self): # Does this line need to be changed?
        """Returns whether two trees are equivalent.

        >>> t1 = Tree(1, [Tree(2, [Tree(3), Tree(4)]), Tree(5, [Tree(6)]), Tree(7)])
        >>> t1 == t1
        True
        >>> t2 = Tree(1, [Tree(2, [Tree(3), Tree(4)]), Tree(5, [Tree(6)]), Tree(7)])
        >>> t1 == t2
        True
        >>> t3 = Tree(0, [Tree(2, [Tree(3), Tree(4)]), Tree(5, [Tree(6)]), Tree(7)])
        >>> t4 = Tree(1, [Tree(5, [Tree(6)]), Tree(2, [Tree(3), Tree(4)]), Tree(7)])
        >>> t5 = Tree(1, [Tree(2, [Tree(3), Tree(4)]), Tree(5, [Tree(6)])])
        >>> t1 == t3 or t1 == t4 or t1 == t5
        False
        """
        "*** YOUR CODE HERE ***"