-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathBinaryTreeTraversals.scala
48 lines (39 loc) · 1.13 KB
/
BinaryTreeTraversals.scala
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
/*
Implement different traversals of a tree
*/
object BinaryTreeTraversals extends App {
case class Tree[A](value: A, left: Option[Tree[A]], right: Option[Tree[A]]) {
def foldInorder[B](b: B)(f: (B, A) => B): B = {
val l = left.fold(b) { _.foldInorder(b)(f) }
val current = f(l, value)
right.fold(current) { _.foldInorder(current)(f) }
}
def foldPreorder[B](b: B)(f: (B, A) => B): B = {
val current = f(b, value)
val l = left.fold(current) { _.foldInorder(current)(f) }
right.fold(l) { _.foldInorder(l)(f) }
}
def foldPostorder[B](b: B)(f: (B, A) => B): B = {
val l = left.fold(b) { _.foldInorder(b)(f) }
val r = right.fold(l) { _.foldInorder(l)(f) }
f(r, value)
}
}
// test
val tree = Tree(
".",
Some(Tree(
"L",
Some(Tree("LL", None, None)),
Some(Tree("LR", None, None))
)),
Some(Tree(
"R",
Some(Tree("RL", None, None)),
Some(Tree("RR", None, None))
))
)
println(tree.foldPreorder("")(_ + " -> " + _))
println(tree.foldPostorder("")(_ + " -> " + _))
println(tree.foldInorder("")(_ + " -> " + _))
}