Skip to content

Instantly share code, notes, and snippets.

@AnthonyBY
Last active November 4, 2017 16:26
Show Gist options
  • Save AnthonyBY/2a63b9bf5aa2f453ec7900ee0538e591 to your computer and use it in GitHub Desktop.
Save AnthonyBY/2a63b9bf5aa2f453ec7900ee0538e591 to your computer and use it in GitHub Desktop.
Day 22: Binary Search Trees (Swift 3.1)
// Start of Node class
class Node {
var data: Int
var left: Node?
var right: Node?
init(d : Int) {
data = d
}
} // End of Node class
// Start of Tree class
class Tree {
func insert(root: Node?, data: Int) -> Node? {
if root == nil {
return Node(d: data)
}
if data <= (root?.data)! {
root?.left = insert(root: root?.left, data: data)
} else {
root?.right = insert(root: root?.right, data: data)
}
return root
}
func getHeight(root: Node?) -> Int {
// Complete the function
var leftHight = 0
var rightHight = 0
var leftRoot = root
var rightRoot = root
while !((leftRoot?.left) == nil) {
leftRoot = leftRoot?.left
leftHight += 1
}
while !((rightRoot?.right) == nil) {
rightRoot = rightRoot?.right
rightHight += 1
}
return max(leftHight, rightHight)
} // End of getHeight function
} // End of Tree class
var root: Node?
let tree = Tree()
let t = Int(readLine()!)!
for _ in 0..<t {
root = tree.insert(root: root, data: Int(readLine()!)!)
}
print(tree.getHeight(root: root))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment