Graph Theory37 sections · 1633 units
Open in Course

LeetCode 226 Invert Binary Tree - Implementation

Code solution

Here is the solution:

function invertTree(root):
    if root is null:
        return null

    temp = root.left
    root.left = root.right
    root.right = temp

    invertTree(root.left)
    invertTree(root.right)

    return root

You swap the pointers with a temp variable. Then you recurse on the swapped children. The recursion propagates the inversion down the tree. Finally, you return the root.

This runs in O(n)O(n) time and uses O(h)O(h) space.