Skip to content

Instantly share code, notes, and snippets.

@vukcevich
Created September 20, 2017 16:41
Show Gist options
  • Select an option

  • Save vukcevich/b03ffd3e772fa52ca38fea2b117632f1 to your computer and use it in GitHub Desktop.

Select an option

Save vukcevich/b03ffd3e772fa52ca38fea2b117632f1 to your computer and use it in GitHub Desktop.
Swift -- recursion with binary tree
import UIKit
//Reference:
//https://medium.com/@Dougly/recursion-with-a-binary-tree-swift-3-748bbefc2cec
//Using Loop
func countDownLoop(from number: Int) {
var i = number
while i > 0 {
print(i)
i -= 1
}
}
countDownLoop(from: 5)
print("\n-----\n")
//Recursive
func countDown(from number: Int) {
print(number)
if number > 1 {
countDown(from: number - 1)
}
}
countDown(from: 5)
print("\n-----\n")
print("Recursion - Binary tree: \n")
//Binary Tree -- is data structure that starts with a root node with up to 2 child nodes branching off of it. The left node is always less then the parent and the right child node is always greater then the parent. Each child node can then be parent to 2 of its own children. In a binary tree if a node has no children it is referred to as a leaf.
//If we are searching for a number in the tree at each node we will want to decide wether we should look to the left or right and we can do this with a recursive function.
class Node {
var value:Int
var leftChild: Node?
var rightChild: Node?
init(value:Int, leftChild: Node?, rightChild: Node?) {
self.value = value
self.leftChild = leftChild
self.rightChild = rightChild
}
}
func find(_ number:Int, with rootNode:Node) -> Bool {
print(rootNode.value)
if(rootNode.value == number) {
return true
} else if rootNode.value < number && rootNode.rightChild != nil {
let result = find(number, with: rootNode.rightChild!)
print(rootNode.value)
return result
} else if rootNode.value > number && rootNode.leftChild != nil {
let result = find(number, with: rootNode.leftChild!)
print(rootNode.value)
return result
}
return false
}
let sevenNode = Node(value: 7, leftChild:nil, rightChild:nil)
let nineNode = Node(value: 9, leftChild:sevenNode, rightChild:nil)
let twoNode = Node(value: 2, leftChild:nil, rightChild:nil)
let threeNode = Node(value: 3, leftChild:twoNode, rightChild:nineNode)
let sixteenNode = Node(value: 16, leftChild:nil, rightChild:nil)
let twelveNode = Node(value: 12, leftChild:nil, rightChild:sixteenNode)
let tenNode = Node(value: 10, leftChild:threeNode, rightChild:twelveNode)
print(find(7, with: tenNode))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment