Bird
Raised Fist0
DSA Javaprogramming

Check if Two Trees are Symmetric in DSA Java

Choose your learning style10 modes available
Mental Model
Two trees are symmetric if one is a mirror image of the other. We compare nodes in opposite positions step-by-step.
Analogy: Imagine folding a paper with a tree drawn on each side. If both sides match perfectly when folded, the trees are symmetric.
    Tree1           Tree2 (mirror)
      1                 1
     / \               / \
    2   3             3   2
   /                   \ 
  4                     4

Pointers compare nodes across trees:
Tree1: 1 -> 2 -> 4
Tree2: 1 -> 3 -> 4
Compare Tree1.left with Tree2.right and Tree1.right with Tree2.left
Dry Run Walkthrough
Input: Tree1: 1->2->4 (left child), 1->3 (right child); Tree2: 1->3->4 (left child), 1->2 (right child)
Goal: Check if Tree2 is the mirror image of Tree1, meaning they are symmetric
Step 1: Compare root nodes of both trees
Tree1: [1] -> 2 -> 3
Tree2: [1] -> 3 -> 2
Why: Roots must be equal to start symmetry check
Step 2: Compare Tree1.left (2) with Tree2.right (2)
Tree1.left: [2] -> 4
Tree2.right: [2]
Why: Left subtree of Tree1 must mirror right subtree of Tree2
Step 3: Compare Tree1.right (3) with Tree2.left (3)
Tree1.right: [3]
Tree2.left: [3] -> 4
Why: Right subtree of Tree1 must mirror left subtree of Tree2
Step 4: Compare Tree1.left.left (4) with Tree2.right.right (null)
Tree1.left.left: [4]
Tree2.right.right: null
Why: One side has node, other side null means not symmetric here
Step 5: Compare Tree1.right.right (null) with Tree2.left.left (4)
Tree1.right.right: null
Tree2.left.left: [4]
Why: Mismatch in structure means trees are not symmetric
Result:
Trees are not symmetric because leaf nodes do not mirror each other
Annotated Code
DSA Java
class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int val) { this.val = val; }
}

public class SymmetricTrees {
    public static boolean isSymmetric(TreeNode t1, TreeNode t2) {
        if (t1 == null && t2 == null) return true;
        if (t1 == null || t2 == null) return false;
        if (t1.val != t2.val) return false;
        return isSymmetric(t1.left, t2.right) && isSymmetric(t1.right, t2.left);
    }

    public static void main(String[] args) {
        TreeNode tree1 = new TreeNode(1);
        tree1.left = new TreeNode(2);
        tree1.right = new TreeNode(3);
        tree1.left.left = new TreeNode(4);

        TreeNode tree2 = new TreeNode(1);
        tree2.left = new TreeNode(3);
        tree2.right = new TreeNode(2);
        tree2.left.right = new TreeNode(4);

        boolean result = isSymmetric(tree1, tree2);
        System.out.println(result);
    }
}
if (t1 == null && t2 == null) return true;
both nodes null means symmetric at this branch
if (t1 == null || t2 == null) return false;
one node null and other not means asymmetry
if (t1.val != t2.val) return false;
values differ means trees not symmetric
return isSymmetric(t1.left, t2.right) && isSymmetric(t1.right, t2.left);
recursively check left subtree of one with right subtree of other and vice versa
OutputSuccess
false
Complexity Analysis
Time: O(n) because each node in both trees is visited once during the recursive check
Space: O(h) where h is the height of the tree due to recursion stack
vs Alternative: Compared to iterative approaches, recursion is simpler but uses stack space; iterative may use explicit stack but similar time complexity
Edge Cases
Both trees are empty (null)
Returns true since empty trees are symmetric
DSA Java
if (t1 == null && t2 == null) return true;
One tree is empty, other is not
Returns false because structure differs
DSA Java
if (t1 == null || t2 == null) return false;
Trees have same values but different structure
Returns false due to mismatch in node positions
DSA Java
return isSymmetric(t1.left, t2.right) && isSymmetric(t1.right, t2.left);
When to Use This Pattern
When a problem asks if two trees are mirror images or symmetric, use a recursive check comparing opposite children nodes to confirm symmetry.
Common Mistakes
Mistake: Comparing left subtree with left subtree and right with right instead of cross comparison
Fix: Compare left subtree of one tree with right subtree of the other and vice versa
Mistake: Not checking for null nodes before accessing values
Fix: Always check if nodes are null before comparing their values
Summary
Checks if two trees are mirror images by recursively comparing opposite children nodes.
Use when you need to verify if two trees are symmetric in structure and values.
The key insight 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 have identical left subtrees only.
B. They have the same number of nodes.
C. They are mirror images of each other around their center.
D. They have the same root value 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 C
  4. Quick Check:

    Symmetry means mirror image = D [OK]
Hint: Symmetric trees mirror each other exactly [OK]
Common Mistakes:
  • Thinking same number of nodes means symmetric
  • Only comparing root values
  • Ignoring structure differences
2. Which Java method signature correctly defines a function to check if two trees are symmetric?
easy
A. public boolean isSymmetric(TreeNode root1, TreeNode root2)
B. boolean isSymmetric(TreeNode root1, TreeNode root2) {}
C. public void isSymmetric(TreeNode root1, TreeNode root2)
D. public boolean isSymmetric(TreeNode root)

Solution

  1. Step 1: Identify correct return type and parameters

    The method should return boolean and accept two TreeNode parameters for two trees.
  2. Step 2: Check method signature syntax

    Public access, boolean return, and parameter types match in public boolean isSymmetric(TreeNode root1, TreeNode root2).
  3. Final Answer:

    public boolean isSymmetric(TreeNode root1, TreeNode root2) -> Option A
  4. Quick Check:

    Correct signature returns boolean with two TreeNode inputs [OK]
Hint: Boolean return with two TreeNode inputs is needed [OK]
Common Mistakes:
  • Using void return type
  • Missing public keyword
  • Using only one TreeNode parameter
3. What will be the output of the following code snippet?
TreeNode root1 = new TreeNode(1);
root1.left = new TreeNode(2);
root1.right = new TreeNode(3);
TreeNode root2 = new TreeNode(1);
root2.left = new TreeNode(3);
root2.right = new TreeNode(2);

System.out.println(isSymmetric(root1, root2));

public static boolean isSymmetric(TreeNode t1, TreeNode t2) {
    if (t1 == null && t2 == null) return true;
    if (t1 == null || t2 == null) return false;
    return (t1.val == t2.val) && isSymmetric(t1.left, t2.right) && isSymmetric(t1.right, t2.left);
}
medium
A. Runtime exception
B. false
C. Compilation error
D. true

Solution

  1. Step 1: Analyze tree structure and values

    root1 has left=2, right=3; root2 has left=3, right=2, which are mirror images.
  2. Step 2: Trace recursive calls

    Values match and recursive calls check mirrored children, all return true.
  3. Final Answer:

    true -> Option D
  4. Quick Check:

    Mirror structure and values = true [OK]
Hint: Check mirrored nodes and values recursively [OK]
Common Mistakes:
  • Ignoring mirrored child comparison
  • Confusing left and right children
  • Assuming same structure means false
4. Identify the bug in this code snippet that checks if two trees are symmetric:
public boolean isSymmetric(TreeNode t1, TreeNode t2) {
    if (t1 == null && t2 == null) return true;
    if (t1 == null || t2 == null) return false;
    return (t1.val == t2.val) && isSymmetric(t1.left, t2.left) && isSymmetric(t1.right, t2.right);
}
medium
A. It compares left with left and right with right instead of mirrored children.
B. It does not check for null nodes.
C. It returns true when both nodes are null.
D. It uses incorrect return type.

Solution

  1. Step 1: Review recursive calls for symmetry

    The code compares t1.left with t2.left and t1.right with t2.right, which checks identical structure, not mirror.
  2. Step 2: Identify correct mirrored comparison

    It should compare t1.left with t2.right and t1.right with t2.left for symmetry.
  3. Final Answer:

    It compares left with left and right with right instead of mirrored children. -> Option A
  4. Quick Check:

    Mirror check needs cross child comparison [OK]
Hint: Mirror check swaps left and right children [OK]
Common Mistakes:
  • Comparing same side children instead of mirrored
  • Ignoring null checks
  • Wrong return type usage
5. Given two binary trees, write a Java method to check if they are symmetric. Which approach correctly solves this problem? A) Traverse both trees in preorder and compare node values in order. B) Recursively check if left subtree of first tree is mirror of right subtree of second tree and vice versa. C) Compare the height of both trees and return true if equal. D) Check if both trees have the same number of leaf nodes.
hard
A. Traverse both trees in preorder and compare node values in order.
B. Recursively check if left subtree of first tree is mirror of right subtree of second tree and vice versa.
C. Compare the height of both trees and return true if equal.
D. Check if both trees have the same number of leaf nodes.

Solution

  1. Step 1: Understand symmetry check requirements

    Symmetry means one tree is mirror image of the other, so left subtree of one matches right subtree of other.
  2. Step 2: Evaluate approaches

    Recursively check if left subtree of first tree is mirror of right subtree of second tree and vice versa. correctly uses recursive mirror checks; others ignore structure or order.
  3. Final Answer:

    Recursively check if left subtree of first tree is mirror of right subtree of second tree and vice versa. -> Option B
  4. Quick Check:

    Mirror recursive check solves symmetry [OK]
Hint: Mirror recursive check is key to symmetry [OK]
Common Mistakes:
  • Using preorder traversal comparison
  • Comparing only height or leaf counts
  • Ignoring mirrored subtree checks
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