☰ All problems

38. Invert Binary Tree

Given the root of a binary tree, mirror it: at every node, the left and right subtrees trade places. Return the root of the mirrored tree.

Picture holding the tree up to a mirror. Whatever was on the far left ends up on the far right, at every level.

Example 1
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Explanation: Each level reads right-to-left after the swap: 2,7 becomes 7,2 and 1,3,6,9 becomes 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 is in the range [0, 100]
  • -100 <= Node.val <= 100
💡 Hint 1

If you already had the mirrored versions of both subtrees, how would you build the mirror of the whole tree?

💡 Hint 2

Swap left and right at the current node, then recurse into both children. The empty tree is its own mirror.

💡 Hint 3

An iterative BFS or DFS works too: pop a node, swap its children, push the non-null ones.

/**
 * Definition for a binary tree node (provided):
 * function TreeNode(val, left, right) { this.val = val ?? 0; this.left = left ?? null; this.right = right ?? null; }
 *
 * @param {TreeNode} root
 * @return {TreeNode}
 */
function invertTree(root) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc