Recursive
boolean isSymmetric(Node root) {
return root == null || isMirror(root.left, root.right);
}
boolean isMirror(Node a, Node b) {
if (a == null && b == null) return true;
if (a == null || b == null) return false;
return a.val == b.val
&& isMirror(a.left, b.right)
&& isMirror(a.right, b.left);
}Advertisement
Iterative with queue
Queue q = new LinkedList<>();
q.offer(root.left); q.offer(root.right);
while (!q.isEmpty()) {
Node a = q.poll(), b = q.poll();
if (a == null && b == null) continue;
if (a == null || b == null || a.val != b.val) return false;
q.offer(a.left); q.offer(b.right);
q.offer(a.right); q.offer(b.left);
}
return true; Advertisement
Value comparison + structural mirror
Both required. Same values in mirrored positions.
Complexity
O(N) time, O(H) space recursive or O(W) iterative.