Blind 75
25 / 75Free practice

Invert Binary Tree

Easy · Trees

Jump to code

Swap the left and right children at every node of a binary tree and return its root. An empty tree stays empty.

Examples

Example 1

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

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

Example 2

root = [2,1,3]

Output: [2,3,1]

Constraints

  • 0 <= The number of nodes in the tree <= 100
  • -100 <= Node.val <= 100

Function contract

Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.

Need a hint?

The same operation applies independently to every subtree.

Asked in real interviews

Candidates reported versions of Invert Binary Tree from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 7 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    4,
    2,
    7,
    1,
    3,
    6,
    9
  ]
]
Expected
[
  4,
  7,
  2,
  9,
  6,
  3,
  1
]
Case 2
Input
[
  [
    2,
    1,
    3
  ]
]
Expected
[
  2,
  3,
  1
]
Case 3
Input
[
  []
]
Expected
[]
Case 4
Input
[
  [
    1
  ]
]
Expected
[
  1
]
Case 5
Input
[
  [
    1,
    2,
    3,
    4,
    5,
    6,
    7
  ]
]
Expected
[
  1,
  3,
  2,
  7,
  6,
  5,
  4
]

Drafts are saved per language in this browser when storage is available.