-
Notifications
You must be signed in to change notification settings - Fork 3
/
Day 23; BST Level-Order Traversal.swift
65 lines (51 loc) · 1.39 KB
/
Day 23; BST Level-Order Traversal.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
58
59
60
61
62
63
64
65
// 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 levelOrder(root: Node?) -> Void {
var array: [[Int]] = []
func bf(node: Node, depth: Int) {
if array.count < depth + 1 {
array.append([])
}
array[depth].append(node.data)
if let leftNode = node.left {
bf(node: leftNode, depth: depth + 1)
}
if let rightNode = node.right {
bf(node: rightNode, depth: depth + 1)
}
}
bf(node: root!, depth: 0)
array.forEach {
$0.forEach {
print($0, terminator: " ")
}
}
} // End of levelOrder 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()!)!)
}
tree.levelOrder(root: root)