-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathday 22.swift
51 lines (38 loc) · 1.08 KB
/
day 22.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
// 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 {
if let currentRoot = root {
let leftHeight = getHeight(root: currentRoot.left)
let rightHeight = getHeight(root: currentRoot.right)
return 1 + max(leftHeight, rightHeight)
}
return -1
}
} // 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))