Post

Created by @oliverrichards
 at November 27th 2023, 8:20:45 pm.

Question:

Write a function to determine if a binary tree is symmetric. A binary tree is symmetric if it is mirror image of itself across the root node. For example, the following binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

Your function should take the root of the binary tree as input and return true if the tree is symmetric, false otherwise.

Answer:

# Define the structure 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


def isSymmetric(root):
    # Helper function to check if two nodes are mirror images of each other
    def isMirror(node1, node2):
        if not node1 and not node2:
            return True
        if not node1 or not node2:
            return False
        return (node1.val == node2.val) and isMirror(node1.left, node2.right) and isMirror(node1.right, node2.left)

    # If the root is None, it is symmetric
    if not root:
        return True
    # Return the result of the isMirror function for the left and right subtrees of the root
    return isMirror(root.left, root.right)


# Create a symmetric binary tree as shown in the example
root = TreeNode(1, TreeNode(2, TreeNode(3), TreeNode(4)), TreeNode(2, TreeNode(4), TreeNode(3)))
# Check if the tree is symmetric
print(isSymmetric(root))  # Output: True

Explanation:

  1. We first define the structure for a binary tree node using the TreeNode class.
  2. We define a helper function isMirror to check if two nodes are mirror images of each other.
  3. Within the isMirror function, we compare the values of the two nodes and recursively check if their left and right subtrees are mirror images of each other.
  4. The isSymmetric function checks if the input tree is symmetric by calling the isMirror function for the left and right subtrees of the root, and returns the result.
  5. Finally, we create a symmetric binary tree as shown in the example and test the isSymmetric function to check if the tree is symmetric, which returns True.