-
Notifications
You must be signed in to change notification settings - Fork 3
/
Day 22; Binary Search Tree.swift
57 lines (44 loc) · 1.22 KB
/
Day 22; Binary Search Tree.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 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 {
var maxHeight: Int = 0
func bf(node: Node, count: Int) {
if count > maxHeight { maxHeight = count }
if let leftNode = node.left {
bf(node: leftNode, count: count + 1)
}
if let rightNode = node.right {
bf(node: rightNode, count: count + 1)
}
}
bf(node: root!, count: 0)
return maxHeight
} // 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))