Check if a binary tree is symmetric

A tree is a mirror of itself when its left and right subtrees mirror each other at every level.

Time O(n)Space O(h)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Symmetry means the left subtree and right subtree are mirror images of one another: equal values, with the left subtree's left matching the right subtree's right, and the left subtree's right matching the right subtree's left. Compare the two subtrees of the root pairwise, crossing sides at every step, the same way two different trees would be compared, but on one tree compared against itself.

Code

public static bool IsSymmetric(TreeNode root) {
    return root == null || IsMirror(root.left, root.right);
}
public static bool IsMirror(TreeNode t1, TreeNode t2) {
    if (t1 == null && t2 == null) return true;
    if (t1 == null || t2 == null || t1.val != t2.val) return false;
    return IsMirror(t1.left, t2.right) && IsMirror(t1.right, t2.left);
}

Tips

In the .NET library

A BST built from distinct keys is essentially never symmetric by value, since left keys are always smaller and right keys always larger. This check matters for plain binary trees, not search trees.