v9.1.1
Menu

Invert Binary Tree

easyFREETreesBlind 75

Given the root of a binary tree (as a level-order array), invert it (mirror/flip left and right children recursively).

Output the level-order traversal of the inverted tree as space-separated values. A missing child that comes before a later node is written as null; trailing nulls are omitted, and an empty tree gives an empty string.

Example

Input
4,2,7,1,3,6,9
Output
4 7 2 9 6 3 1
Reasoning
  • Input: 4,2,7,1,3,6,9 lists the tree level by level, left to right. Level 0 is the root 44; level 1 holds its children 22 (left) and 77 (right); level 2 holds 1,31, 3 under 22 and 6,96, 9 under 77.
  • Mirroring reflects the tree across a vertical line through the root. Every node keeps its value and its depth, but its two subtrees trade sides, and the same reflection applies inside each subtree.
  • After the reflection the root 44 has 77 on the left and 22 on the right. Under 77 the children 6,96, 9 become 9,69, 6; under 22 the children 1,31, 3 become 3,13, 1.
  • Reading the mirrored tree level by level, left to right: 44, then 7,27, 2, then 9,6,3,19, 6, 3, 1, giving 4 7 2 9 6 3 1.
  • Notice that for a complete tree like this one, each level of the output is simply that level of the input reversed. A missing child in the middle of a level would show up as a null placeholder on the mirrored side.

Constraints

  • 0 <= number of nodes <= 100
  • -100 <= Node.val <= 100

Learn this in

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.