Created
August 27, 2017 17:50
-
-
Save NickHung1982/1022d3dd3c05ebe09e93a935a1d69712 to your computer and use it in GitHub Desktop.
Binary Search Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Tree | |
class Tree { | |
var root: Node? | |
func addValue(_ val: Int) { | |
let newNode = Node(value: val) | |
if self.root == nil { | |
print("root value is \(val)") | |
self.root = newNode | |
}else{ | |
root?.addNode(newNode) | |
} | |
} | |
func traverse() { | |
root?.visit() | |
} | |
} | |
//nodes | |
class Node { | |
var value: Int | |
var leftChild: Node? | |
var rightChild: Node? | |
init(value: Int) { | |
self.value = value | |
} | |
func addNode(_ n: Node) { | |
if n.value < self.value { | |
if self.leftChild == nil { | |
self.leftChild = n | |
}else{ | |
self.leftChild?.addNode(n) | |
} | |
}else if (n.value > self.value){ | |
if self.rightChild == nil { | |
self.rightChild = n | |
}else{ | |
self.rightChild?.addNode(n) | |
} | |
} | |
} | |
func visit(){ | |
if self.leftChild != nil { | |
self.leftChild?.visit() | |
} | |
print(self.value) | |
if self.rightChild != nil { | |
self.rightChild?.visit() | |
} | |
} | |
} | |
//******** Create Tree ******* | |
let newTree = Tree() | |
//Use random to add nodes | |
for _ in 0...10 { | |
let randomNum:UInt32 = arc4random_uniform(100) | |
newTree.addValue(Int(randomNum)) | |
} | |
//show all tree node from smallest to largest | |
newTree.traverse() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment