- Easy
- Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
- https://leetcode.com/problems/symmetric-tree/
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
else:
return self.isMirror(root.left,root.right)
def isMirror(self,left,right):
if not (left or right):
return True
if (not left) or (not right):
return False
if left.val==right.val:
inpair=self.isMirror(left.right,right.left)
outpair=self.isMirror(left.left,right.right)
return inpair and outpair
else:
return False
{% hint style="info" %} Recursive Method {% endhint %}
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if root is None:
return True
stack = [[root.left, root.right]]
while stack:
pair = stack.pop()
left = pair[0]
right = pair[1]
if not (left or right):
continue
if (not left) or (not right):
return False
if left.val == right.val:
stack.append([left.left, right.right])
stack.append([left.right, right.left])
else:
return False
return True
{% hint style="info" %} Iterative method. {% endhint %}