Skip to content

Instantly share code, notes, and snippets.

@vukcevich
Created March 29, 2018 16:48
Show Gist options
  • Select an option

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

Select an option

Save vukcevich/bb4bf23e2cd728dcc73fdcf637617e5a to your computer and use it in GitHub Desktop.
Binary Search Tree -- example
import UIKit
class NodeTree<T: Comparable> {
var key: T?
var leftNode:NodeTree?
var rightNode: NodeTree?
init(key:T, leftChild: NodeTree?, rightChild: NodeTree?) {
self.key = key
self.leftNode = leftChild
self.rightNode = rightChild
}
init() {
}
func addNode(key: T) {
//check if head node
if(self.key == nil) {
self.key = key
return
}
//chekc if left side of the tree
if (key < self.key!) {
if(self.leftNode != nil) {
leftNode!.addNode(key:key)
} else {
let leftChild:NodeTree = NodeTree()
leftChild.key = key
self.leftNode = leftChild
}
}
//check the right side of the tree
if (key > self.key!) {
if(self.rightNode != nil) {
rightNode!.addNode(key: key)
} else {
let rightChild:NodeTree = NodeTree()
rightChild.key = key
self.rightNode = rightChild
}
}
} //end of function addNode
}
//a simple array of unsorted integers
let numberList : Array<Int> = [8, 2, 10, 9, 11, 1, 7]
//create a new BST instance
var root = NodeTree<Int>()
//sort each item in the list
for number in numberList {
root.addNode(key:number)
}
print("root:", root)
@vukcevich
Copy link
Author

Simple Example of Binary Search Tree --- coding test for iOS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment