EasyTreeDepth-First SearchBreadth-First SearchBinary Tree

1 approach, code in every language

Problem description

You are given the root of a binary tree. Produce the mirror image of that tree by swapping the left and right child of every node, then return the (unchanged) root reference.

Inverting a tree means that at each node the two subtrees trade places, and this swap is applied all the way down to the leaves. After the operation, an in-order walk of the tree reads in reverse compared to the original.

Example 1

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

Output: [4,7,2,9,6,3,1]

Every node keeps its value, but each node's left and right children are swapped, so 2 and 7 trade places, and beneath them 1/3 and 6/9 trade places as well.

Example 2

Input: root = [2,1,3]

Output: [2,3,1]

The root keeps value 2 while its children 1 and 3 swap sides.

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

After the pattern

Now solve one you haven't seen.

Mirror The Splitter Harness is our own problem on the technique behind Invert Binary Tree: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free