Skip to content
RED SAGSkills
easy15 ptstreerecursion

Mirror a Binary Tree

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 layout engine needs to render a right-to-left version of a tree. Swap the left and right children of every node, so the whole tree becomes its mirror image.

Return trees in the same level-order format, with any trailing null entries removed.

Example 1

Input: tree = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Explanation: Every node swaps its two children.

Example 2

Input: tree = [2,1,3]
Output: [2,3,1]

Constraints

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

Visit every node once (any order) and swap its two child pointers.

Hint 2

Then write the tree back out with a breadth-first traversal.

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 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.