Skip to problem
←

Symmetric Tree

Easy 0 attempts

Given the root of a binary tree, determine whether it looks the same when reflected across its vertical center — in other words, whether the left and right subtrees are mirror images of each other.

Both node values and missing-child positions must match under reflection. Compare the left child on one side with the right child on the other side, and vice versa. A single-node tree is symmetric. Matching values at each depth alone is not sufficient.

Function contract

Implement isSymmetric(root). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return true only if both values and left/right structure match under reflection; otherwise return false.

Example 1

Input
root = [1,2,2,3,4,4,3]
Output
true

Example 2

Input
root = [1,2,2,null,3,null,3]
Output
false

Explanation: Both nodes with value 3 are right children. Reflection would require one to be a left child, so the shapes do not mirror each other.

Constraints
  • 1 <= number of nodes <= 1000
  • -100 <= Node.val <= 100

Recursive Mirror Check

javascript
function isSymmetric(root) {
  function isMirror(a, b) {
    if (!a && !b) return true;
    if (!a || !b || a.val !== b.val) return false;
    return isMirror(a.left, b.right) && isMirror(a.right, b.left);
  }
  return isMirror(root, root);
}

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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript