Skip to content
CodeKruPro

Check whether a binary tree is a mirror of itself

Coding problemEasyAsked in: Adobe, Amazon, Apple, Google, Meta, Microsoft

Given the root of a binary tree, return true if the tree is symmetric around its centre, and false otherwise. A tree is symmetric when its left subtree is a mirror image of its right subtree: same values, with left and right swapped at every level.

Trees are written in level order, with null for a missing child. An empty tree and a single node are symmetric.

Examples

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
Both 3s are right children; a mirror needs one left and one right.
Example 3
Input: root = []
Output: true

Constraints

  • The tree has between 0 and 100,001 nodes
  • Each value is a 32-bit integer

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in