Skip to problem
←

Invert Binary Tree

Easy 0 attempts

Return the mirror image of the binary tree rooted at root: swap the left and right children at every node, preserving all node values. You may modify the tree in place.

Return the resulting root node. An empty input returns null; a single-node tree remains unchanged.

Function contract

root is a binary-tree node with val, left, and right properties, or null. Test inputs use level-order arrays with null for missing children; [] becomes null.

Output: Return the root node of the mirrored tree, or null for an empty tree. The runner displays level-order values with trailing nulls omitted.

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]

Explanation: The root remains 2; its left child becomes 3 and its right child becomes 1.

Example 3

Input
root = []
Output
[]
Constraints
  • 0 <= number of nodes <= 100
  • -100 <= Node.val <= 100

Approach: Recursive DFS

For each node, swap its left and right children, then recursively invert both subtrees. Base case: null node returns null.

javascript
function invertBinaryTree(root) {
  if (!root) return null;
  [root.left, root.right] = [root.right, root.left];
  invertBinaryTree(root.left);
  invertBinaryTree(root.right);
  return root;
}

Time Complexity: O(n)

Space Complexity: O(h) where h is tree height

Loading discussion…

Saved in this browser only. Private to you.

JavaScript