Invert Binary Tree

Easy#226tree nodes

You get the root of a binary tree. Turn it into its mirror image: at every node, the left and right children trade places, and return the root. Our tree: 6 with children 2 and 9; 2 has children 1 and 4, 9 has only a right child 8 — the answer: 6 with children 9 and 2; 9 now has only a left child 8, and 2 has children 4 and 1.

input
root: a binary tree, written as on LeetCode: its values level by level, left to right, null for a missing child.
returns
The root of the tree mirrored: every node's left and right children swapped. Changing the given tree is fine.
constraints
  • 0 ≤ the number of nodes ≤ 1000
  • −100 ≤ Node.val ≤ 100
our 10 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
function invertTree(root) {

}
Ctrl ↵
format
reset

saved in this browser

10 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more depth-first search (dfs) problems

Pattern “Depth-first search (DFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.