Created
August 5, 2023 08:11
-
-
Save ponnamkarthik/3909fb467c66b8e464addf0fd0405b71 to your computer and use it in GitHub Desktop.
Symmetric Tree - LeetCode 101 (Easy)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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