Here is an implementation of a function that inverts a binary tree using recursive approach in Swift:
main.swift402 chars22 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.swift239 chars10 lines
This will create the following original binary tree:
main.swift50 chars6 lines
and apply the inversion function to result in the following inverted binary tree:
main.swift50 chars6 lines
gistlibby LogSnag