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

Invert Binary Tree

binary tree · recursion

Inverting (mirroring) a binary tree swaps the left and right children of every node, so the tree you get is the reflection of the original.

Given the root of a binary tree, invert it and return its root.

Examples

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

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

Input:  root = [2, 1, 3]
Output: [2, 3, 1]
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…