Bird
Raised Fist0
DSA Pythonprogramming

Check if Two Trees are Symmetric in DSA Python

Choose your learning style10 modes available
Mental Model
Two trees are symmetric if one is a mirror image of the other, meaning their shapes and node values match when flipped.
Analogy: Imagine folding a paper with a tree drawn on one side; if the other side matches perfectly when folded, the trees are symmetric.
Tree1:       1           Tree2:       1
           /   \                   /   \
          2     3                 3     2
         /       \               /       \
        4         5             5         4
Dry Run Walkthrough
Input: Tree1: 1 -> 2, 3 -> 4, 5; Tree2: 1 -> 3, 2 -> 5, 4
Goal: Check if Tree2 is the mirror image of Tree1
Step 1: Compare root nodes of both trees
Tree1 root=1, Tree2 root=1
Why: Roots must be equal for symmetry
Step 2: Compare left child of Tree1 (2) with right child of Tree2 (2)
Tree1 left=2, Tree2 right=2
Why: Mirror nodes must match in value
Step 3: Compare right child of Tree1 (3) with left child of Tree2 (3)
Tree1 right=3, Tree2 left=3
Why: Mirror nodes must match in value
Step 4: Compare left child of Tree1's left (4) with right child of Tree2's right (4)
Tree1 left.left=4, Tree2 right.right=4
Why: Mirror nodes must match in value
Step 5: Compare right child of Tree1's right (5) with left child of Tree2's left (5)
Tree1 right.right=5, Tree2 left.left=5
Why: Mirror nodes must match in value
Result:
Trees are symmetric because all corresponding mirror nodes match in value and structure
Annotated Code
DSA Python
class TreeNode:
    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
    if t1.val != t2.val:
        return False
    # Recursively check mirror symmetry
    return is_symmetric(t1.left, t2.right) and is_symmetric(t1.right, t2.left)

# Build Tree1
root1 = TreeNode(1)
root1.left = TreeNode(2)
root1.right = TreeNode(3)
root1.left.left = TreeNode(4)
root1.right.right = TreeNode(5)

# Build Tree2
root2 = TreeNode(1)
root2.left = TreeNode(3)
root2.right = TreeNode(2)
root2.left.left = TreeNode(5)
root2.right.right = TreeNode(4)

result = is_symmetric(root1, root2)
print("Symmetric" if result else "Not symmetric")
if not t1 and not t2:
both nodes are empty, so symmetric here
if not t1 or not t2:
one node is empty but other is not, so not symmetric
if t1.val != t2.val:
node values differ, so not symmetric
return is_symmetric(t1.left, t2.right) and is_symmetric(t1.right, t2.left)
recursively check mirror children pairs
OutputSuccess
Symmetric
Complexity Analysis
Time: O(n) because we visit each node once to compare
Space: O(h) due to recursion stack where h is tree height
vs Alternative: Compared to flattening trees to arrays and reversing, this approach is more memory efficient and direct
Edge Cases
Both trees are empty
Returns True since empty trees are symmetric
DSA Python
if not t1 and not t2:
One tree is empty, other is not
Returns False since structure differs
DSA Python
if not t1 or not t2:
Trees have different values at mirror nodes
Returns False due to value mismatch
DSA Python
if t1.val != t2.val:
When to Use This Pattern
When asked if two trees are mirror images, use recursive checks comparing left subtree of one with right subtree of the other.
Common Mistakes
Mistake: Comparing left subtree with left subtree instead of left with right
Fix: Compare t1.left with t2.right and t1.right with t2.left to check mirror symmetry
Mistake: Not checking for null nodes before accessing values
Fix: Add null checks before value comparison to avoid errors
Summary
Checks if two trees are mirror images by comparing nodes recursively.
Use when you need to verify if one tree is symmetric to another.
The key is to compare left subtree of one tree with right subtree of the other and vice versa.

Practice

(1/5)
1. What does it mean for two binary trees to be symmetric?
easy
A. They are mirror images of each other around their center.
B. They have the same number of nodes.
C. They have the same root value only.
D. They have identical left subtrees only.

Solution

  1. Step 1: Understand symmetry in trees

    Two trees are symmetric if one is the mirror reflection of the other around the center.
  2. Step 2: Compare structure and node values

    Both structure and node values must match in a mirrored way for symmetry.
  3. Final Answer:

    They are mirror images of each other around their center. -> Option A
  4. Quick Check:

    Symmetry means mirror image = A [OK]
Hint: Symmetric trees mirror each other exactly [OK]
Common Mistakes:
  • Thinking same number of nodes means symmetric
  • Ignoring node values in comparison
  • Checking only left or right subtree
2. Which of the following Python function signatures is correct to check if two trees are symmetric?
easy
A. def is_symmetric(tree1, tree2)
B. def is_symmetric(tree1 tree2):
C. def is_symmetric(tree1, tree2) -> bool:
D. def is_symmetric(tree1, tree2): return True

Solution

  1. Step 1: Check syntax for function definition

    Python functions require parentheses around parameters and a colon at the end.
  2. Step 2: Identify correct type hint usage

    def is_symmetric(tree1, tree2) -> bool: uses correct syntax with type hint and colon, making it valid and clear.
  3. Final Answer:

    def is_symmetric(tree1, tree2) -> bool: -> Option C
  4. Quick Check:

    Correct Python function syntax with type hint = D [OK]
Hint: Use parentheses and colon; type hints are optional but clear [OK]
Common Mistakes:
  • Missing comma between parameters
  • Omitting colon at function end
  • Incorrect parameter syntax without parentheses
3. What will be the output of the following code snippet?
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def is_mirror(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_mirror(t1.left, t2.right) and is_mirror(t1.right, t2.left)

root1 = Node(1)
root1.left = Node(2)
root1.right = Node(3)

root2 = Node(1)
root2.left = Node(3)
root2.right = Node(2)

print(is_mirror(root1, root2))
medium
A. True
B. False
C. None
D. Error

Solution

  1. Step 1: Check base cases for empty nodes

    Both trees have root 1, and their left and right children are swapped but equal in value.
  2. Step 2: Recursively verify mirror condition

    Left of root1 (2) matches right of root2 (2), and right of root1 (3) matches left of root2 (3), so all conditions return True.
  3. Final Answer:

    True -> Option A
  4. Quick Check:

    Mirror check returns True for swapped children = A [OK]
Hint: Mirror means left of one equals right of other [OK]
Common Mistakes:
  • Confusing left and right children in recursion
  • Ignoring base cases for None nodes
  • Assuming same structure means symmetric
4. Identify the error in this code snippet that checks if two trees are symmetric:
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
    if t1.val != t2.val:
        return False
    return is_symmetric(t1.left, t2.left) and is_symmetric(t1.right, t2.right)
medium
A. It does not check for None nodes.
B. It compares left with left and right with right instead of mirror sides.
C. It returns True too early without checking values.
D. It uses 'is' instead of '==' for value comparison.

Solution

  1. Step 1: Analyze recursive calls for symmetry

    The function compares left subtree of t1 with left subtree of t2 and right with right, which is incorrect for mirror symmetry.
  2. Step 2: Correct mirror comparison

    It should compare left of t1 with right of t2 and right of t1 with left of t2 to check mirror symmetry properly.
  3. Final Answer:

    It compares left with left and right with right instead of mirror sides. -> Option B
  4. Quick Check:

    Mirror check requires cross comparison = B [OK]
Hint: Mirror means cross compare left with right [OK]
Common Mistakes:
  • Comparing same sides instead of mirror sides
  • Confusing 'is' and '==' for values
  • Missing base cases for None nodes
5. Given two binary trees, write a function to check if they are symmetric considering that one tree might be None. Which approach correctly handles this edge case?
hard
A. Return False immediately if either tree is None.
B. Ignore None checks and compare node values only.
C. Only compare root values and ignore subtrees.
D. Return True if both trees are None, else check mirror recursively.

Solution

  1. Step 1: Handle None edge cases carefully

    If both trees are None, they are symmetric by definition, so return True.
  2. Step 2: Recursively check mirror symmetry

    If only one is None, return False. Otherwise, compare root values and recursively check left of one with right of other and vice versa.
  3. Final Answer:

    Return True if both trees are None, else check mirror recursively. -> Option D
  4. Quick Check:

    Both None means symmetric, else recurse mirror check = C [OK]
Hint: Both None means symmetric; one None means not symmetric [OK]
Common Mistakes:
  • Returning False if either tree is None without checking both
  • Skipping recursive mirror checks
  • Comparing only root values
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard