Invert Binary Tree
1 min read

Invert Binary Tree

Invert a binary tree.

Example:

Input

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

Output:

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

The solution is a simple recursive approach:

  • Call invert for left-subtree.
  • Call invert for right-subtree.
  • Swap left and right subtrees.

fun invertTree(root: TreeNode?): TreeNode? {
    if (root == null) {
        return null
    }
    val right = invertTree(root.right)
    val left = invertTree(root.left)
    root.left = right
    root.right = left
    return root
}

The solution assumes that the binary tree is already created