Problem 495523 · easy · Level 04 Non-Linear Data Structures

Mirror Image of a Tree

binary tree · recursion

Hold a drawing of a binary tree up to a mirror and, at every node, the left and right children trade places. That reflection is what this problem builds, one swap per node.

Write invert_tree(root) that turns the tree into its mirror image by swapping the two children of every node, and returns the root of the mirrored tree (None for an empty tree).

Examples

     6                 6
   /   \             /   \
  3     8    -->    8     3
 / \   / \         / \   / \
1   4 7   9       9   7 4   1

Input:  root = [6, 3, 8, 1, 4, 7, 9]
Output: [6, 8, 3, 9, 7, 4, 1]
    5           5
   /             \
  9      -->      9
 /                 \
7                   7

Input:  root = [5, 9, None, 7]
Output: [5, None, 9, None, 7]
Input:  root = []
Output: []

Constraints

  • 0 <= number of nodes <= 1000

Goals

  • Modify a tree in place during a recursive traversal
  • Return the root so the caller can use the transformed tree
  • Swap two attributes with tuple assignment
Starting Python…