Problem List/Day 9Invert Binary Tree
LeetCode

Invert Binary Tree

EasyTrees & DFSDay 9

Problem Statement

Given the root of a binary tree, invert the tree (swap left and right children for every node), and return its root.

Examples (Test Cases & Output)

Example 1:
Input: root = [4, 2, 7, 1, 3, 6, 9]
Output: [4, 7, 2, 9, 6, 3, 1]
Example 2:
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

Target Complexities

Optimal TimeO(N)
Optimal SpaceO(H) where H is tree height
Core Algorithmic Insight:

Remember to store one child in a temporary variable before recursing or swapping to avoid overwriting pointers mid-execution.

Active Mode:Optimal Solution
Time: O(N)•Space: O(H) where H is tree height
Loading VS Code Hack Editor...
How This Code Works:

Recursive Depth-First Search (DFS): Base case if root === null return null. Recursively call invertTree on root.left and root.right, swap the two pointers, and return root.