Invert Binary Tree

Medium~15 min

Given the root of a binary tree, invert the tree, and return its root.

Inverting a binary tree means swapping every left child with its corresponding right child, for all nodes in the tree.

Each node has a val (integer value), a left pointer, and a right pointer. Leaf nodes point to null on both sides.

Examples

Example 1
Input: root = [4, 2, 7, 1, 3, 6, 9]
Output: [4, 7, 2, 9, 6, 3, 1]
Explanation: The tree rooted at 4 has its left subtree [2,1,3] and right subtree [7,6,9] swapped at every level.
Example 2
Input: root = [2, 1, 3]
Output: [2, 3, 1]
Explanation: The left child 1 and right child 3 are swapped.
Example 3
Input: root = [1]
Output: [1]
Explanation: A single-node tree is already its own mirror image.

Constraints

  • The number of nodes in the tree is in the range [0, 100]
  • -100 <= Node.val <= 100
  • Expected time complexity: O(n)
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run