Check whether a binary tree is symmetric
Filed under Deutsche Bank
Free read 1 of 3Confirm symmetry covers values and structure, and an empty tree counts as symmetric.
The question
Given the root of a binary tree, check whether it is symmetric, meaning the left subtree is a mirror image of the right subtree in both structure and node values.
Constraints
- 0 <= number of nodes <= 1000.
- An empty tree is symmetric.
Examples
- Input
- [1,2,2,3,4,4,3]
- Output
- True
- Why
- Left subtree 2(3,4) mirrors right subtree 2(4,3).
- Input
- [1,2,2,null,3,null,3]
- Output
- False
- Why
- Both 2s have a right child 3 only, which is not a mirror.
Approach
Confirm symmetry covers values and structure, and an empty tree counts as symmetric.
Mirror a copy of the left subtree, then compare it with the right subtree. O(n) time but builds extra nodes.
Recursive helper mirror(a, b): both None is true, one None is false, else values equal and mirror(a.left, b.right) and mirror(a.right, b.left). Start with the root's two children.
Use a queue of node pairs, pushing (a.left, b.right) and (a.right, b.left). This avoids deep recursion on skewed trees.
Empty tree, single node, equal values but different shape, and a skewed tree.
Solution
O(n) time, O(h) space
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val, self.left, self.right = val, left, right
def is_symmetric(root):
def mirror(a, b):
if not a and not b:
return True
if not a or not b: # shapes differ
return False
return a.val == b.val and mirror(a.left, b.right) and mirror(a.right, b.left)
return mirror(root, root) if root else True
Tips
- What they are testing: Tests recursion on two nodes at once and careful base cases for None.
- Common mistake: Comparing the left subtree to the right subtree directly instead of left.left with right.right and left.right with right.left.
Related Deutsche Bank questions
Collected from public candidate posts and coding forums. Updated Nov 2026.