Symmetric Tree

Pattern: Depth, diameter and balance

easy

A tree is symmetric when its left subtree is the mirror image of its right subtree. Two subtrees are mirrors when their roots match, the outer pair (left of one, right of the other) are mirrors, and so are the inner pair.

The problem

Return whether the tree is a mirror of itself around its centre. [1, 2, 2, 3, 4, 4, 3] is true; [1, 2, 2, null, 3, null, 3] is false. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • What two subtrees must be compared?
  • Which children are matched with which?
  • How is this like Same Tree?

Hints

    Brute force, and why it fails

    Build the mirror image and compare it with the tree: O(n) but twice the memory.

    The key insight

    Comparing the tree with itself in crossed order checks the mirror property without building anything.

    Dry run

    [1, 2, 2, 3, 4, 4, 3]. Compare the two 2s: equal.

    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)
    return mirror(root.left, root.right)
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    Each mirrored pair is compared once.

    Edge cases

    • Empty tree: true.
    • One node: true.
    • Same values but wrong shape: false.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean isSymmetric(TreeNode root) {
            return root == null || mirror(root.left, root.right);
        }
    
        private boolean mirror(TreeNode a, TreeNode b) {   // is a the mirror image of b?
            if (a == null || b == null) return a == b;
            return a.val == b.val && mirror(a.left, b.right) && mirror(a.right, b.left);   // outside with outside, inside with inside
        }
    }

    C++

    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            return root == NULL || mirror(root->left, root->right);
        }
    
        bool mirror(TreeNode* a, TreeNode* b) {     // is a the mirror image of b?
            if (a == NULL || b == NULL) return a == b;
            return a->val == b->val && mirror(a->left, b->right) && mirror(a->right, b->left);   // outside, then inside
        }
    };

    Python

    class Solution:
        def isSymmetric(self, root) -> bool:
            def mirror(a, b) -> bool:               # is a the mirror image of b?
                if not a or not b:
                    return a is b
                return a.val == b.val and mirror(a.left, b.right) and mirror(a.right, b.left)   # outside, then inside
    
            return root is None or mirror(root.left, root.right)

    Common mistakes

    • Comparing left with left.
    • Checking only that each level reads the same both ways (shape matters).

    Similar problems