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#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

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);
}
static boolean isSymmetric(TreeNode root) {
    return root == null || isMirror(root.left, root.right);
}

static boolean 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);
}
bool isMirror(TreeNode* t1, TreeNode* t2);

bool isSymmetric(TreeNode* root) {
    return !root || isMirror(root->left, root->right);
}

bool isMirror(TreeNode* t1, TreeNode* t2) {
    if (!t1 && !t2) return true;
    if (!t1 || !t2 || t1->val != t2->val) return false;
    return isMirror(t1->left, t2->right) && isMirror(t1->right, t2->left);
}
def is_symmetric(root: TreeNode | None) -> bool:
    return root is None or is_mirror(root.left, root.right)

def is_mirror(t1: TreeNode | None, t2: TreeNode | None) -> bool:
    if t1 is None and t2 is None: return True
    if t1 is None or t2 is None or t1.val != t2.val: return False
    return is_mirror(t1.left, t2.right) and is_mirror(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.