create a function that inverts a binary tree in swift

Here is an implementation of a function that inverts a binary tree using recursive approach in Swift:

main.swift
class TreeNode {
    var value: Int
    var left: TreeNode?
    var right: TreeNode?

    init(_ value: Int) {
        self.value = value
    }
}

func invertBinaryTree(_ root: TreeNode?) -> TreeNode? {
    guard let root = root else { return nil }

    let left = invertBinaryTree(root.left)
    let right = invertBinaryTree(root.right)

    root.left = right
    root.right = left

    return root
}
402 chars
22 lines

This function takes in the root node of a binary tree and recursively inverts it by swapping the left and right child nodes of each node. The function returns the new root node after the inversion.

To use this function, you can create a binary tree using the TreeNode class and call invertBinaryTree function passing in the root node:

main.swift
let root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(7)
root.left?.left = TreeNode(1)
root.left?.right = TreeNode(3)
root.right?.left = TreeNode(6)
root.right?.right = TreeNode(9)

let invertedRoot = invertBinaryTree(root)
239 chars
10 lines

This will create the following original binary tree:

main.swift
      4
     / \
    2   7
   / \ / \
  1  3 6  9
50 chars
6 lines

and apply the inversion function to result in the following inverted binary tree:

main.swift
      4
     / \
    7   2
   / \ / \
  9  6 3  1
50 chars
6 lines

gistlibby LogSnag