101. Symmetric Tree
[Medium] “Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center)."
Python3:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
else:
return self.checkSymmetric(root.left, root.right)
def checkSymmetric(self, left: TreeNode, right: TreeNode):
if not left and not right:
# symmetric terminal nodes
return True
elif (not left and right) or (left and not right):
# one node terminal when other isn't
return False
elif left.val == right.val:
# check further
outside = self.checkSymmetric(left.left, right.right)
inside = self.checkSymmetric(left.right, right.left)
return outside and inside
else:
# not symmetric
return False