Start learning free

LESSON 352 OF 443 · BINARY TREES

Invert Binary Tree in Swift

Practice O(n)

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

Inverting a tree mirrors it from left to right: at every node, the left child and the right child trade places, all the way down to the leaves.

The trees below are written in level order (top to bottom, left to right), with nil for a missing child. The test results print a tree the same way, with spaces between the values, -1 for a missing child and the trailing ones left out: [4,7,2,9,6,3,1] prints as 4 7 2 9 6 3 1, and an empty tree prints as -1.

 

Example 1:

       4                       4
     /   \                   /   \
    2     7       →         7     2
   / \   / \               / \   / \
  1   3 6   9             9   6 3   1

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Explanation: 2 and 7 trade places under the root, then 1 and 3 under 2, and 6 and 9 under 7.

Example 2:

      1                1
     /                  \
    2         →          2
   /                      \
  3                        3

Input: root = [1,2,nil,3]
Output: [1,nil,2,nil,3]
Explanation: Every left child becomes a right child, so a line going left becomes a line going right.

Example 3:

Input: root = []
Output: []
Explanation: An empty tree has nothing to swap: it is its own mirror.

 

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • Each node value is between 0 and 100.
  • The tree is at most 400 levels deep.

 

Follow up: Can you do it in O(n) time, visiting each of the n nodes only once?
STEP 1 OF 5
    Ctrl + Enter to check

    Invert Binary Tree in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free