Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Invert a Tree

Treesmedium

Implement `invertTree(root)` returning a new tree that is the mirror image (left and right swapped at every node).

Sample tests

Input: invertTree({"val":1,"left":{"val":2,"left":null,"right":null},"right":{"val":3,"left":null,"right":null}})
Output: {"val":1,"left":{"val":3,"left":null,"right":null},"right":{"val":2,"left":null,"right":null}}
Input: invertTree(null)
Output: null

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Mutating the original tree instead of returning a new one.

Learning resources

  • Wikipedia: Binary tree
Approach & explanation (try first)

Recursively swapping left and right children mirrors the tree. O(n).

Loading...
⌘/Ctrl + Enter

Run your code to see results.