101. Symmetric Tree
# Easy
Be careful with edge case in compare()
function.
root1 = None & roo2 = None
root1 = None & root2 != None
root1 != None & roo2 = None
# 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: TreeNode) -> bool:
# edge case
if root == None:
return True
# regular case
root1 = root.left
root2 = root.right
return self.compare(root1, root2)
def compare(self, root1, root2):
# stop condition
if root1 == None and root2 == None:
return True
if (root1 != None and root2 == None) or (root1 == None and root2 != None):
return False
# regular case
if root1.val == root2.val:
a1 = self.compare(root1.left, root2.right)
a2 = self.compare(root1.right, root2.left)
if a1 == True and a2 == True:
return True
else:
return False
Last updated
Was this helpful?