Given a binary tree, check whether it is a symmetric tree. A symmetric tree is a mirror image of itself with respect to its center.

Function Signature:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def is_symmetric(root: TreeNode) -> bool:
    """
    Check if a binary tree is symmetric.

    Parameters:
    - root: The root of the binary tree.

    Returns:
    - bool: True if the binary tree is symmetric, False otherwise.
    """
    # Your code here

Example:

# Example Symmetric Binary Tree:
#        1
#       / \
#      2   2
#     / \ / \
#    3  4 4  3
symmetric_tree = TreeNode(1, 
	                      TreeNode(2, 
	                      	       TreeNode(3), 
	                      	       TreeNode(4)
	                      	       ), 
	                      TreeNode(2, 
	                      	       TreeNode(4), 
	                      	       TreeNode(3)
	                      	       )
	                      )
result_symmetric = is_symmetric(symmetric_tree)
print(result_symmetric)
assert result_symmetric is True
# Explanation: The left subtree is the mirror of the right subtree

# Example Non-Symmetric Binary Tree:
#        1
#       / \
#      2   2
#       \   \
#        3    3
non_symmetric_tree = TreeNode(1,
	                          TreeNode(2, 
	                          	       None, 
	                          	       TreeNode(3)
	                          	       ), 
	                          TreeNode(2, 
	                          	       None,
	                          	       TreeNode(3)
	                          	       )
	                          )
result_non_symmetric = is_symmetric(non_symmetric_tree)
print(result_non_symmetric)
assert result_non_symmetric is False
# Explanation: The left subtree has the same structure as the right subtree, but they do not mirror each other. 

Note:

  • The given binary tree is not necessarily a binary search tree.
  • All node values are unique.

Instructions:

  • Write the is_symmetric function to solve the problem.
  • Implement your solution in Python.
  • Provide clear comments in your code.
  • Discuss the time and space complexity of your solution.

As always, we’ll share our solution to this problem tomorrow. Stay tuned 😊