Problem 3.1: Equal Trees (100 pts)
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 spcial 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).
Note: unlike problem 6.2 in midterm exam, this time we require two equivalent trees should have branches in the same order.
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 ***"