Learnitweb

Symmetric Tree

1. Problem statement

Given the root of a binary tree, check whether the tree is symmetric around its center.

In simple terms:
A binary tree is symmetric if the left subtree is a mirror of the right subtree.

Example 1: Symmetric Tree

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

Output: true

Example 2: Not Symmetric

        1
       / \
      2   2
       \   \
       3    3

Output: false

2. Recursive Java Solution

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int val) { this.val = val; }
}

public class SymmetricTree {

    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        return isMirror(root.left, root.right);
    }

    private boolean isMirror(TreeNode t1, TreeNode t2) {
        // Both nodes are null: symmetric
        if (t1 == null && t2 == null) return true;
        // Only one is null: not symmetric
        if (t1 == null || t2 == null) return false;

        // Check values and mirror children
        return (t1.val == t2.val)
            && isMirror(t1.left, t2.right)
            && isMirror(t1.right, t2.left);
    }
}

3. Explanation

  • Compare the left and right nodes
  • Then recursively compare:
    • left subtree of left node with right subtree of right node
    • right subtree of left node with left subtree of right node

4. Iterative Java Solution (Using Queue)

You can also solve this using a queue to avoid recursion.

import java.util.*;

public class SymmetricTreeIterative {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root.left);
        queue.add(root.right);

        while (!queue.isEmpty()) {
            TreeNode t1 = queue.poll();
            TreeNode t2 = queue.poll();

            if (t1 == null && t2 == null) continue;
            if (t1 == null || t2 == null) return false;
            if (t1.val != t2.val) return false;

            // Add children in mirror order
            queue.add(t1.left);
            queue.add(t2.right);
            queue.add(t1.right);
            queue.add(t2.left);
        }

        return true;
    }
}