Skip to the solution
EasyDSA11 min read

How do you check if a binary tree is symmetric?

342 views

The problem

Question presented to candidate: "Given the root of a binary tree, write a Python function that returns True if the tree is a mirror of itself โ€” symmetric around its centre โ€” and False otherwise. Can you do it both recursively and iteratively?"

What a strong answer should cover:

  • Reduce the problem to a two-argument mirror check: is_mirror(root.left, root.right).
  • The four cases: both None, exactly one None, different values, then outer pair and inner pair.
  • An iterative version with a deque of node pairs (pairs containing None are fine).
  • O(n) time, O(h) recursion or O(w) queue space; why an inorder palindrome check is wrong.
  • Python specifics: compare values with ==, not is (is tests object identity and fails for larger ints built at runtime); and short-circuits; the recursion limit of 1000 limits the recursive version on deep trees.

Clarifying questions expected:

  • "Must the shape mirror as well as the values?"
  • "Should an empty tree count as symmetric?"

Code / implementation expected: Yes โ€” a recursive Python helper on two nodes, and ideally an iterative queue-of-pairs version.

  • trees
  • recursion

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonRecursive mirror check on six trees
PythonIterative queue of pairs, the wrong inorder-palindrome idea, and a 100001-node V tree

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 30 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you find the single number where every other element appears twice?

Continue