Symmetric Tree
Difficulty: Easy · Pattern: Trees & BST · LeetCode #101
Given the root of a binary tree, check whether it is a mirror of itself, meaning symmetric around its center.
Examples
text
1 1
/ \ / \
2 2 2 2
/ \ / \ \ \
3 4 4 3 3 3
→ true → falseHints
- A tree is symmetric when its left and right subtrees are mirror images of each other.
- Two trees
aandbare mirrors whena.val == b.val,a.leftmirrorsb.right, anda.rightmirrorsb.left.
Approach
Write a helper mirror(a, b). It works like Same Tree, but the recursion crosses over:
mirror(a.left, b.right): the outer pairmirror(a.right, b.left): the inner pair
The answer is mirror(root.left, root.right). An iterative BFS version puts the pairs in a queue in that crossed order.
Complexity
Time: O(n). Space: O(h).
Python solution
def isSymmetric(root):
def 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 mirror(a.left, b.right) and mirror(a.right, b.left)
return mirror(root.left, root.right) if root else TrueJavaScript solution
function isSymmetric(root) {
const mirror = (a, b) => {
if (!a && !b) return true;
if (!a || !b || a.val !== b.val) return false;
return mirror(a.left, b.right) && mirror(a.right, b.left);
};
return root ? mirror(root.left, root.right) : true;
}