Invert Binary Tree

IF
AlgoAxiomStaff Engineers
JSTS
Easy20 mins

Given the root of a binary tree, invert the tree by swapping the left and right children of all nodes and return its root.

Examples

Example 1:

4271369

Input: root = [4, 2, 7, 1, 3, 6, 9]

Output: [4, 7, 2, 9, 6, 3, 1]

Explanation: The tree is mirrored — every left child is swapped with its corresponding right child.

Example 2:

213

Input: root = [2, 1, 3]

Output: [2, 3, 1]

Example 3:

Input: root = []

Output: []

Constraints

  • The number of nodes in the tree is in the range [0, 100]
  • -100 <= Node.val <= 100
Source: Tree Depth-First Search pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle