noodleProblems/
Invert Binary Tree
#130

Invert Binary Tree

AlgorithmeasyTreeDepth First SearchBreadth First SearchBinary Tree

Given the root of a binary tree, invert it — swap the left and right child of *every* node — and return the new root.

Inverting is a mirror operation: the resulting tree is the reflection of the original across a vertical line through the root.

The tree is given as a level-order array where null marks a missing child: [2, 1, 3] is root 2 with children 1 and 3.

Example cases

  • balanced
    in root = [4,2,7,1,3,6,9]1234679
    out [4,7,2,9,6,3,1]9764321
    Each node's children swap: 2↔7, 1↔3, 6↔9.
  • small
    in root = [2,1,3]123
    out [2,3,1]321
  • empty
    in root = []null
    out []null

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
Saved
root =
[4,2,7,1,3,6,9]