Scala algorithm: Print a binary tree
Published
Algorithm goal
Print a binary tree, efficiently, in a human-readable fashion, such as:
Node(v=1, l=Node(v=2, l=Node(v=4, l=Node(v=6, l=, r=), r=), r=), r=Node(v=3, l=, r=Node(v=4, l=, r=Node(v=5, l=, r=Node(v=7, l=, r=)))))
Becoming:
1
|-- 2
|-- 4
|-- 6
|-- 3
|-- 4
|-- 5
|-- 7
Test cases in Scala
assert(stringValue { BinaryTree.Node(1) } == """1""")
assert(stringValue {
BinaryTree.Node(1).copy(right = BinaryTree.Node(2))
} == List("1", "|-- 2").mkString("\n"))
assert(stringValue {
BinaryTree
.Node(1)
.copy(right = BinaryTree.Node(2).copy(right = BinaryTree.Node(3)))
} == List("1", "|-- 2", " |-- 3").mkString("\n"))
assert(stringValue {
BinaryTree
.Node(1)
.copy(
left = BinaryTree
.Node(2)
.copy(left = BinaryTree.Node(4).copy(left = BinaryTree.Node(6))),
right = BinaryTree
.Node(3)
.copy(right =
BinaryTree
.Node(4)
.copy(right = BinaryTree.Node(5).copy(right = BinaryTree.Node(7)))
)
)
} == List("1", "|-- 2", " |-- 4", " |-- 6", "|-- 3", " |-- 4", " |-- 5", " |-- 7").mkString("\n"))
assert(stringValue {
BinaryTree
.Node(1)
.copy(
left = BinaryTree.Node(4),
right = BinaryTree.Node(2).copy(right = BinaryTree.Node(3))
)
} == List("1", "|-- 4", "|-- 2", " |-- 3").mkString("\n"))
Algorithm in Scala
31 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
Explanation
This is not a particularly complex algorithm; however we do have to be mindful of efficiency. One thing to note is that we pass the depth
value to the child of stringValuePadded, so we would not have to do additional remapping of the results that are returned. (this is © from www.scala-algorithms.com)
Scala concepts & Hints
Lazy List
The 'LazyList' type (previously known as 'Stream' in Scala) is used to describe a potentially infinite list that evaluates only when necessary ('lazily').
Pattern Matching
Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.