Checking if a Binary Tree is a Mirror Image of Itself

Given a binary tree, this function checks whether it is symmetrical around its center. For example, the first tree in the input is symmetrical, but the second one is not.


Given a binary tree, write a function to check whether it is a mirror image of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
But the following is not:
Output: True


This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSymmetric(self, root):
        :type root: TreeNode
        :rtype: bool
        if root is None:
            return True
        return self.isSymmetricRecur(root.left, root.right)
    def isSymmetricRecur(self, left, right):
        if left is None or right is None:
            return left == right
        if left.val != right.val:
            return False
        return self.isSymmetricRecur(left.left, right.right) and self.isSymmetricRecur(left.right, right.left)

A.I. Evaluation of the Solution

The candidate's solution correctly implements a recursive solution to check if a binary tree is symmetric. The approach is sound, and the code is clean and easy to follow.

Evaluated at: 2022-12-03 12:15:26