-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trees_BinaryTreeTraversal.swift
103 lines (84 loc) · 1.84 KB
/
Trees_BinaryTreeTraversal.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import UIKit
class BinaryNode<Element> {
var value: Element
var leftChild: BinaryNode?
var rightChild: BinaryNode?
init(_ value: Element) {
self.value = value
}
}
extension BinaryNode {
func inOrderTraversal(visit: (Element) -> Void) { // leftChild -> Node -> RightChild
leftChild?.inOrderTraversal(visit: visit)
visit(value)
rightChild?.inOrderTraversal(visit: visit)
}
func postOrderTraversal(visit: (Element) -> Void) { // leftChild -> RightChild -> Node
leftChild?.postOrderTraversal(visit: visit)
rightChild?.postOrderTraversal(visit: visit)
visit(value)
}
func preOrderTraversal(visit: (Element) -> Void) { // Node -> leftChild -> rightChild
visit(value)
leftChild?.preOrderTraversal(visit: visit)
rightChild?.preOrderTraversal(visit: visit)
}
}
/* 10
/ \
9 2
/ \ / \
1 3 4 6
*/
let ten = BinaryNode(10)
let nine = BinaryNode(9)
let two = BinaryNode(2)
let one = BinaryNode(1)
let three = BinaryNode(3)
let four = BinaryNode(4)
let six = BinaryNode(6)
ten.leftChild = nine
ten.rightChild = two
nine.leftChild = one
nine.rightChild = three
two.leftChild = four
two.rightChild = six
print("\nIn Order Traversal")
ten.inOrderTraversal {
print($0) //1 9 3 10 4 2 6
}
print("\nPost Order Traversal")
ten.postOrderTraversal {
print($0) // 1 3 9 4 6 2 10
}
print("\nPre Order Traversal")
ten.preOrderTraversal {
print($0) //10 9 1 3 2 4 6
}
/*
Outputs printed:
In Order Traversal
1
9
3
10
4
2
6
Post Order Traversal
1
3
9
4
6
2
10
Pre Order Traversal
10
9
1
3
2
4
6
*/