Skip to content

Instantly share code, notes, and snippets.

@thexande
Created September 4, 2018 02:23
Show Gist options
  • Select an option

  • Save thexande/77a0bc56bee9f8f92641e6269f240df5 to your computer and use it in GitHub Desktop.

Select an option

Save thexande/77a0bc56bee9f8f92641e6269f240df5 to your computer and use it in GitHub Desktop.
A Recursive in order Binary Tree Traversal implementation
/// BinaryTree data structure for a recursive tree
///
/// - node: the root node
/// - empty: empty node
/// - value: The underlying data within the node
indirect enum BinaryTree<T> {
case node(BinaryTree<T>, T, BinaryTree<T>)
case empty
var value: T? {
switch self {
case let .node(_, data, _):
return data
default:
return nil
}
}
}
// Bottom left leaves
let ten = BinaryTree.node(.empty, 10, .empty)
let fortyNine = BinaryTree.node(.empty, 49, .empty)
// Bottom right leaf
let ninetyNine = BinaryTree.node(.empty, 99, .empty)
// Middle left tree
let twentyFive = BinaryTree.node(ten, 25, fortyNine)
// Middle right tree
let seventyFive = BinaryTree.node(.empty, 75, ninetyNine)
// Root node
let root = BinaryTree.node(twentyFive, 50, seventyFive)
/// A Recursive in order Binary Tree Traversal implementation
/// Check if the current node is empty or null.
/// Traverse the left subtree by recursively calling the in-order function.
/// Display the data part of the root (or current node).
/// Traverse the right subtree by recursively calling the in-order function.
/// - Parameter root: the root node of the tree
func recursiveInOrderBinaryTreeTraversal<T>(root: BinaryTree<T>?) {
guard let root = root else {
return
}
if case let .node(left, _, _) = root {
recursiveInOrderBinaryTreeTraversal(root: left)
}
if let val = root.value {
print(val)
}
if case let .node(_, _, right) = root {
recursiveInOrderBinaryTreeTraversal(root: right)
}
}
recursiveInOrderBinaryTreeTraversal(root: root)
// prints
// 10
// 25
// 49
// 50
// 75
// 99
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment