Is a binary tree its own mirror? Compare the left and right subtrees in pairs: outer with outer, inner with inner, all the way down.
▼The problem
LeetCode 101 (Easy). Given the root of a binary tree, return whether it is a mirror of itself around its centre.
Examples (LeetCode's): [1,2,2,3,4,4,3] → true (walked through in scene 6) and [1,2,2,null,3,null,3] → false (scene 7: the outer pair is empty against 3, so the inner pair is never checked).
def is_symmetric(root):
def is_mirror(a, b):
if not a and not b:
return True
if not a or not b or a.val != b.val:
return False
return (is_mirror(a.left, b.right) and
is_mirror(a.right, b.left))
return is_mirror(root.left, root.right)TRY IT ON LEETCODE ▶The solution
def is_symmetric(root):
def is_mirror(a, b):
if not a and not b:
return True
if not a or not b or a.val != b.val:
return False
return (is_mirror(a.left, b.right) and
is_mirror(a.right, b.left))
return is_mirror(root.left, root.right)Transcript
Symmetric Tree. You get the root of a binary tree. Is it a mirror image of itself? Picture a butterfly: fold it down the middle, and every spot on the left wing should land on an equal spot on the right.
Here's one. One on top, two and two below it, then three, four, four, three. Fold it, and every spot lands on its twin: true. In this second tree, both threes hang to the right. Fold it, and the left three lands on an empty spot: false.
The obvious way: build a mirrored copy of the whole tree, then compare the two, node by node. That's O of n time, but the copy costs O of n extra space, a whole second tree just to check a shape.
Better: skip the copy and compare the wings directly, one pair of spots at a time. Two spots mirror each other if their values match, their outer children mirror, and their inner children mirror. Two empty spots match. One empty spot against a real one doesn't.
In code, is mirror takes a pair. Both empty: true. Only one empty, or different values: false. Otherwise, check the outer pair and the inner pair. Start with the root's two children.
Let's walk the first tree. Two and two match. Outer pair: three and three match, and their empty children match too. Inner pair: four and four match, and so do theirs. Every pair holds: true.
Now the second tree. Two and two match again. But the outer pair is empty against three: false, right away. The inner pair is never even checked.
Each node is checked at most once, so the time is O of n. There's no copy; the only extra space is the recursion, one call per level: O of h, the tree's height.
Fold it in your head: outer with outer, inner with inner. That's Symmetric Tree.