Solution for problem on slide 3:
Basically use the previous solution for "same tree" but mirror the nodes that need to be equivalent. Let a be the left child of the node and b be the right child of the root. Each left node of a must have the same value as the right nodes of b and vice versa.
def isMirrorTree(self, p, q):
if p and q:
return p.val == q.val and self.isSameTree(p.left, q.right) and self.isSameTree(p.right, q.left)
return p is q
def isSymmetric(self, root):
return self.isSameTree(root.left, root.right)
Solution for problem on. slide 6 (HW):
This is another classic recursive problem. Given a node check the max depths of its children. return the maximum of those depths +1 (as you are counting the current node in the max depth).
max_depth = 0
if root:
if root.left:
max_depth = max(max_depth, self.maxDepth(root.left)
if root.right:
max_depth = max(max_depth, self.maxDepth(root.right))
max_depth +=1
return max_depth
If you have any questions or comments regarding my solutions feel free to contact me.