Suppose we are given two subtrees, root1 and root2, how can we check that they are symmetric?
First, if root1 and root2 are None we can definitely say that subtrees are symmetric.
Otherwise, we need to check:
def symmetric_roots(root1: Node,root2) -> bool:
if root1 is None and root2 is None:
return True
# ... Add other condtions : return False when the nodes are not symmetric
return symmetric_roots(root1.left,root2.right) and symmetric_roots(root1.right,root2.left)
Of course, we need to think when the subtrees are not symmetric and add those condtions to the recursive function.
The tree is not recursive if :
Let's add those condtions
def symmetric_roots(root1: Node, root2) -> bool:
if root1 is None and root2 is None:
return True
if not root1.left and root2.right or root1.left and not root2.right:
return False
if not root2.left and root1.right or root2.left and not root1.right:
return False
if root1.left and root2.right and root1.left.data != root2.right.data:
return False
if root2.left and root1.right and root2.left.data != root1.right.data:
return False
return symmetric_roots(root1.left, root2.right) and symmetric_roots(root1.right, root2.left)
Now we can easily check if binary is symmetric. Can you explain why?
def symmetric(root: Node) -> bool:
return symmetric_roots(root,root)
The last thing we need to do is to run the tests
$ python -m unittest tests.symetric
. ----------------------------------------------------------------------
OK
Yes, we successfully solved the part 1 of the quiz.
Let's solve the part 2 of the quiz