class Node: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_symmetric(t1, t2): if not t1 and not t2: return True if not t1 or not t2: return False return (t1.val == t2.val) and is_symmetric(t1.left, t2.right) and is_symmetric(t1.right, t2.left) # Construct trees tree1 = Node(1, Node(2), Node(3)) tree2 = Node(1, Node(3), Node(2)) print(is_symmetric(tree1, tree2))
The function is_symmetric recursively checks if two trees are mirror images. Here, tree1 and tree2 are not symmetric because the left child of tree1 does not match the right child of tree2 and vice versa.
class Node: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_symmetric(t1, t2): if not t1 and not t2: return True if not t1 or not t2: return False return (t1.val == t2.val) and is_symmetric(t1.left, t2.right) and is_symmetric(t1.right, t2.left) # Construct tree tree1 = Node(1, Node(2), Node(3)) tree2 = None print(is_symmetric(tree1, tree2))
The function returns False because one tree is None and the other is not, so they cannot be symmetric.
class Node: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_symmetric(t1, t2): if t1 is None and t2 is None: return True if t1 is None or t2 is None: return False return (t1.val == t2.val) and is_symmetric(t1.left, t2.left) and is_symmetric(t1.right, t2.right) # Construct trees tree1 = Node(1, Node(2), Node(3)) tree2 = Node(1, Node(3), Node(2)) print(is_symmetric(tree1, tree2))
The function incorrectly compares left subtree with left subtree and right with right, so it returns False for symmetric trees that are mirror images.
Symmetry means one tree is the mirror image of the other, so left subtree of one matches right subtree of the other.
class Node: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def is_symmetric(t1, t2): if not t1 and not t2: return True if not t1 or not t2: return False return (t1.val == t2.val) and is_symmetric(t1.left, t2.right) and is_symmetric(t1.right, t2.left) # Construct trees tree1 = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6))) tree2 = Node(1, Node(3, Node(6), None), Node(2, Node(5), Node(4))) print(is_symmetric(tree1, tree2))
The trees are mirror images with matching node values in symmetric positions, so the function returns True.
