Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
It's easy to find a solution that works, but I was wondering why my solution doesn't work. The way I tried doing this is the following: first reflect the original tree about the vertical axis passing through the root, and then compare the reflected tree with the original tree. The reflected tree is equal to the original tree iff the original tree is symmetric.
My code is below. It breaks, for example for the input root = [1,2,2,null,3,null,3] -- the output is True instead of False. But I don't see why this is happening; the two internal functions work as intended I believe.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def invertTree(root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
root.left, root.right = invertTree(root.right), invertTree(root.left)
return root
def isSameTree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if p is None and q is None:
return True
elif p is not None and q is None:
return False
elif p is None and q is not None:
return False
elif p.val != q.val:
return False
return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
inverted_root = invertTree(root)
return isSameTree(root, inverted_root)
A quick fix would be: