Algo-Sim › Binary Trees & BST

Symmetric Tree

Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Mirror recursion: compare the outer pair (left.left, right.right) and the inner pair (left.right, right.left).

Problem

Given the root of a binary tree, return true if the tree is a mirror image of itself around its centre, and false otherwise.

Constraints

Edge cases to test

Follow-up questions

Iterative version?
A queue of pairs (left, right): push (l.left, r.right) and (l.right, r.left) for each pair.
Why not compare the inorder lists?
Different shapes can have the same inorder; the recursion checks shape and values together.

Solution

Java

public boolean isSymmetric(TreeNode root) {
    return root == null || mirror(root.left, root.right);
}

private boolean mirror(TreeNode a, TreeNode b) {
    if (a == null && b == null) return true;
    if (a == null || b == null) return false;
    if (a.val != b.val) return false;
    if (!mirror(a.left, b.right)) return false;
    return mirror(a.right, b.left);
}

Python

def is_symmetric(root):
    return root is None or mirror(root.left, root.right)


def mirror(a, b):
    if not a and not b:
        return True
    if not a or not b:
        return False
    if a.val != b.val:
        return False
    if not mirror(a.left, b.right):
        return False
    return mirror(a.right, b.left)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool isSymmetric(TreeNode *root) {
        return root == nullptr || mirror(root->left, root->right);
    }

  private:
    bool mirror(TreeNode *a, TreeNode *b) {
        if (a == nullptr && b == nullptr)
            return true;
        if (a == nullptr || b == nullptr)
            return false;
        if (a->val != b->val)
            return false;
        if (!mirror(a->left, b->right))
            return false;
        return mirror(a->right, b->left);
    }
};

More Binary Trees & BST problems