Skip to content

Instantly share code, notes, and snippets.

@ponnamkarthik
Created August 5, 2023 08:11
Show Gist options
  • Save ponnamkarthik/3909fb467c66b8e464addf0fd0405b71 to your computer and use it in GitHub Desktop.
Save ponnamkarthik/3909fb467c66b8e464addf0fd0405b71 to your computer and use it in GitHub Desktop.
Symmetric Tree - LeetCode 101 (Easy)
# 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:
# Base case for root if it is None then we just simply return true
if not root:
return True
# Recurstion function which will implement cases to check if tree has reached the end or if tree is not mirror
def isMirror(tree1, tree2):
# Case to check if we reached the end of all nodes
if not tree1 or not tree2:
return tree1 == tree2
# Case to check if the values are not matched i.e., this is not a mirror tree
if tree1.val != tree2.val:
return False
# recursion call to check (left , right) and (rigt, left) of the specific tree
return isMirror(tree1.left, tree2.right) and isMirror(tree1.right, tree2.left)
# first call to the recursion function with left and right nodes of root
return isMirror(root.left, root.right)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment