Recursion and Trees
71 / 170Recursion and TreesLesson 4 of 13About 35 min
One walk to visit every node, another to test each one. Two functions, and the cost multiplies.
same_shape checks two trees for an exact match. The pattern here does appear inside the big tree, but not starting at the node being tested. Type the two values it prints, separated by a single space.
class T: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def same_shape(a, b): if a is None and b is None: return True if a is None or b is None: return False return (a.val == b.val and same_shape(a.left, b.left) and same_shape(a.right, b.right)) big = T(3, T(4, T(1), T(2)), T(5))pattern = T(4, T(1), T(2)) print(same_shape(big, pattern), same_shape(big.left, pattern))Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.