I'm working on LeetCode 101 Symmetric Tree in Python: Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Obviously I can find the answer online but I'm trying to really understand everything. My code below returns False even when everything is correct. I have print statements whenever the method should return True or False, and on cases that should be true, it prints True and never False but returns False. Why is it returning False if it's successfully calling print immediately before where it says return True?
Thank you for your patience. Like I said, the answer can be found easily but I'm trying to understand the concepts better.
# 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:
if root.left == None and root.right == None:
return True
if root.left == None or root.right == None:
return False
if root.left.val != root.right.val:
return False
leftside = root.left
rightside = root.right
def checktree(left, right):
if left == None and right == None:
print('true')
return True
if left == None or right == None:
print('false')
return False
if left.val != right.val:
print('false')
return False
checktree(left.left, right.right)
checktree(left.right, right.left)
return checktree(leftside, rightside)