Check if 2 trees are mirror or not

Pattern: Depth, diameter and balance

medium

Two trees are mirrors when both are empty, or their roots are equal, the left of the first mirrors the right of the second, and the right of the first mirrors the left of the second.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Return whether tree b is the mirror image of tree a. [1, 2, 3] and [1, 3, 2] are mirrors. The catalogue has no practice link for this one. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • How does Same Tree compare children?
  • What changes for mirrors?
  • What about empty trees?

Hints

    Brute force, and why it fails

    Mirror one tree and run Same Tree: O(n) with extra work.

    The key insight

    Crossing the children in the Same Tree recursion checks the mirror relation directly.

    Dry run

    a = [1, 2, 3], b = [1, 3, 2]. Roots 1 and 1.

    Step 1 of 3

    The plan

    mirror(a, b): if a or b is null: return a == b
                  return a.val == b.val and mirror(a.left, b.right) and mirror(a.right, b.left)
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    Each pair once.

    Edge cases

    • Both empty.
    • Different sizes.
    • A tree and itself: only if symmetric.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean areMirror(TreeNode a, TreeNode b) {
            if (a == null || b == null) return a == b;
            return a.val == b.val && areMirror(a.left, b.right) && areMirror(a.right, b.left);   // left matches right
        }
    }

    C++

    class Solution {
    public:
        bool areMirror(TreeNode* a, TreeNode* b) {
            if (a == NULL || b == NULL) return a == b;
            return a->val == b->val && areMirror(a->left, b->right) && areMirror(a->right, b->left);   // left matches right
        }
    };

    Python

    class Solution:
        def areMirror(self, a, b) -> bool:
            if not a or not b:
                return a is b
            return a.val == b.val and self.areMirror(a.left, b.right) and self.areMirror(a.right, b.left)   # left matches right

    Common mistakes

    • Comparing left with left.
    • Comparing only traversal lists.

    Similar problems