Data Structures19 sections · 729 units
Open in Course

Symmetric Tree Solution

Compare mirror positions

Create a helper that checks if two trees are mirrors:

function isSymmetric(root):
    if root == null:
        return true
    return isMirror(root.left, root.right)

function isMirror(t1, t2):
    if t1 == null and t2 == null:
        return true
    if t1 == null or t2 == null:
        return false
    return (t1.val == t2.val and
            isMirror(t1.left, t2.right) and
            isMirror(t1.right, t2.left))

The insight: in a mirror, t1t1's left corresponds to t2t2's right, and t1t1's right corresponds to t2t2's left.

Time: O(n)O(n). Space: O(h)O(h).