Skip to content
RED SAGSkills

Is the Tree Its Own Mirror?

A binary tree is given as a level-order array: tree[0] is the root, then the children of each real node are listed left to right, level by level. A missing child is written as null, and the children of a missing node are not listed at all. For example [1,2,3,null,4] is root 1 with children 2 and 3, where 2 has only a right child 4.

A designer wants to know whether a tree-shaped logo looks the same when flipped left to right. Return true if the tree is symmetric around its centre (both shape and values), otherwise false. An empty tree is symmetric.

Example 1

Input: tree = [1,2,2,3,4,4,3]
Output: true
Explanation: The left and right halves are mirror images.

Example 2

Input: tree = [1,2,2,null,3,null,3]
Output: false
Explanation: Both 3s hang on the right, so the halves do not mirror each other.

Constraints

  • 0 <= number of nodes <= 5000
  • 0 <= node value <= 100
Hint 1

Compare the left subtree with the right subtree as a pair.

Hint 2

Two subtrees mirror each other when their roots match, left.left mirrors right.right, and left.right mirrors right.left.

Discussion 0

Join free to post in the discussion.

Good practice for: Frontend Developer, Backend Developer, Full Stack Developer, Mobile App Developer, Game Developer, Automation Test Engineer

Run checks your code on 3 sample tests. Submit runs all 9 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.