Created
March 4, 2019 11:44
-
-
Save miguelfermin/b04de167b51d11698d0d03547f3ce5b5 to your computer and use it in GitHub Desktop.
Binary Tree
This file contains hidden or 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
class Node { | |
var left, right: Node? | |
var data: Int | |
init(data: Int, left: Node? = nil, right: Node? = nil) { | |
self.data = data | |
self.left = left | |
self.right = right | |
} | |
func insert(value: Int) { | |
// if value is less or equal to "data", insert on left side, | |
// otherwise, insert on right. | |
// | |
if value <= data { // insert on left | |
if left == nil { | |
left = Node(data: value) | |
} else { | |
left?.insert(value: value) | |
} | |
} | |
else { // insert on right | |
if right == nil { | |
right = Node(data: value) | |
} else { | |
right?.insert(value: value) | |
} | |
} | |
} | |
func contains(_ value: Int) -> Bool { | |
if value == data { | |
return true | |
} | |
else if value < data { | |
if left == nil { return false } | |
return left!.contains(value) | |
} | |
else { | |
if right == nil { return false } | |
return right!.contains(value) | |
} | |
} | |
func printInOrder() { | |
left?.printInOrder() | |
print(data) | |
right?.printInOrder() | |
} | |
func printPreOrder() { | |
print(data) | |
left?.printInOrder() | |
right?.printInOrder() | |
} | |
func printPostOrder() { | |
left?.printInOrder() | |
right?.printInOrder() | |
print(data) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment