Invert Binary Tree Easy 0 attempts
LeetCode ↗

Invert Binary Tree

Easy TreeBinary TreeDFS LeetCode

Given the root of a binary tree, invert the tree and return its root. Inverting a binary tree means swapping the left and right children of every node in the tree, producing a mirror image of the original tree.

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]
Sample Input
Sample Output
Constraints
  • 0 <= number of nodes <= 100
  • -100 <= Node.val <= 100
Test Cases
Case 1
Args: [[4,2,7,1,3,6,9]] Expected: [4,7,2,9,6,3,1]
Case 2
Args: [[2,1,3]] Expected: [2,3,1]
Case 3
Args: [[]] Expected: []

Approach: Recursive DFS

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

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

Saved in this browser only. Private to you.

JavaScript