CodeSpeek

Invert Binary Tree

Easy · Trees

You are given the root of a binary tree. Return the root of the tree after swapping every node's left and right children throughout the whole tree, so the result is the mirror image of the original. The tree can be empty, in which case there is nothing to invert.

Examples

Input:  root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Why:    Each node's left and right children are swapped recursively, producing the mirrored tree.
Input:  root = [2,1,3]
Output: [2,3,1]
Why:    The two leaves 1 and 3 swap sides under the root.
Input:  root = []
Output: []
Why:    An empty tree has nothing to invert, so the result is still empty.

Constraints

0 <= number of nodes <= 100, -100 <= Node.val <= 100

Practise it by voice

Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.

Practise Invert Binary Tree

This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Invert Binary Tree. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.