Symmetric Tree

EasyBinary Tree · DFS / BFS🧩 Tree DFSLeetCode #101 ↗Updated

Problem

Given the root of a binary tree, decide whether the tree looks the same as its mirror image — i.e. folding it along the vertical line through the root makes the left half land exactly on the right half (same shape, same values).
Input[1,2,2,3,4,4,3]Outputtrue
Input[1,2,2,null,3,null,3]Outputfalse

1 ≤ n ≤ 1000  ·  -100 ≤ Node.val ≤ 100  ·  Follow-up: solve it both recursively and iteratively.

Try it yourself

Java
class Solution {
    public boolean isSymmetric(TreeNode root) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Don't compare a subtree with itself — compare two subtrees as a pair: a and b are mirrors iff their values match, a.left mirrors b.right and a.right mirrors b.left.
PatternTree DFS

Instinct If the answer for a node can be built from the answers of its left and right subtrees, write one recursive function and trust it on the children.

Memory hack Ask the kids, then decide - each child reports up, the parent combines, and a global variable keeps the best "bend" seen so far.

Open the Tree DFS guide →

Approaches

Brute ForceBuild the Mirror, then Compare

Time O(n)Space O(n)

A tree is symmetric exactly when it is identical to its own mirror. So build a fresh mirrored copy (swap left/right at every node), then run a standard “same tree” check between the original and the copy.

Java
public boolean isSymmetric(TreeNode root) {
    return same(root, mirror(root));
}
private TreeNode mirror(TreeNode t) {
    if (t == null) return null;
    return new TreeNode(t.val, mirror(t.right), mirror(t.left));
}
private boolean same(TreeNode a, TreeNode b) {
    if (a == null || b == null) return a == b;
    return a.val == b.val && same(a.left, b.left) && same(a.right, b.right);
}

Reuses two well-known routines, but allocates a full copy of the tree.

At a glance

LevelApproachTimeSpace
Brute ForceBuild the Mirror, then CompareO(n)O(n)
BetterIterative BFS on Node PairsO(n)O(w)
OptimalRecursive Mirror CheckO(n)O(h)
Common pitfalls
  • Comparing a.left with b.left — that checks equality, not mirroring.
  • Checking only values level by level — [1,2,2,null,3,null,3] has palindromic values but wrong shape.
  • Using ArrayDeque for the queue — it throws on null; use LinkedList.
Interview tips
  • Say the mirror rule out loud: values equal, outer pair mirrors, inner pair mirrors.
  • Offer both recursive and iterative versions — it is the stated follow-up.
  • Test aloud on a single node, a two-level tree and a shape-only mismatch.
Pattern
Two-tree simultaneous DFS → compare/merge two trees (or two halves of one) node by node.
My notes saved in this browser