# Scala algorithm: Print a binary tree vertically

Published

## Algorithm goal

Print a binary tree into a String form, such as:

`````` 1
┌┴─┐
2  3
| ┌┴─┐
4 2  4
|    |
6    5
┌┴┐
9 7``````

Begin with this definition of a Binary Tree:

``final case class Node[T](value: T, left: Option[Node[T]] = None, right: Option[Node[T]] = None)``

## Test cases in Scala

``````assert(
Node(1)
.withLeft(Node(2))
.withRight(Node(3))
.renderTree(_.toString)
.stringValue == " 1 \n┌┴┐\n2 3"
)
assert(
Node(0)
.withLeft(Node(1).withLeft(Node(2)).withRight(Node(3)))
.renderTree(_.toString)
.stringValue == " 0 \n | \n 1 \n┌┴┐\n2 3"
)
assert(Box.direct("1").stack("2").stringValue == "2\n|\n1")
assert(Box.direct("123").centre == 1)
assert(Box.direct("1234").centre == 2)
assert(
Box.direct("1").joinWith("x", Box.direct("2")).stringValue ==
" x \n┌┴┐\n1 2"
)
assert(
Box.direct("1").joinWith("x", Box.direct("234")).stringValue ==
" x   \n┌┴─┐ \n1 234"
)
``````

## Algorithm in Scala

79 lines of Scala (compatible versions 2.13 & 3.0).

## Explanation

The trickiest part of this algorithm is the rendering, rather than the tree traversal.

Given the tree width varies depending on how many leaf nodes there are at the very bottom, we would have to implement this algorithm with a bottom-up approach: . (this is © from www.scala-algorithms.com)

• When we combine two trees, we are putting them side by side, effectively "gluing" them together
• When we create the lines joining the trees, we have some idea of a 'centre' of the left and right trees.
• When we have a parent with a single child node, we just need a direct line down.

## Scala concepts & Hints

1. ### Option Type

The 'Option' type is used to describe a computation that either has a result or does not. In Scala, you can 'chain' Option processing, combine with lists and other data structures. For example, you can also turn a pattern-match into a function that return an Option, and vice-versa!

``````assert(Option(1).flatMap(x => Option(x + 2)) == Option(3))

assert(Option(1).flatMap(x => None) == None)
``````
2. ### Pattern Matching

Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.

``````assert("Hello World".collect {
case character if Character.isUpperCase(character) => character.toLower
} == "hw")
``````
3. ### Range

The `(1 to n)` syntax produces a "Range" which is a representation of a sequence of numbers.

``````assert((1 to 5).toString == "Range 1 to 5")

assert((1 to 5).reverse.toString() == "Range 5 to 1 by -1")

assert((1 to 5).toList == List(1, 2, 3, 4, 5))
``````
4. ### Zip

'zip' allows you to combine two lists pair-wise (meaning turn a pair of lists, into a list of pairs)

It can be used over Arrays, Lists, Views, Iterators and other collections.

``````assert(List(1, 2, 3).zip(List(5, 6, 7)) == List(1 -> 5, 2 -> 6, 3 -> 7))

assert(List(1, 2).zip(List(5, 6, 7)) == List(1 -> 5, 2 -> 6))

assert(List(5, 6).zipWithIndex == List(5 -> 0, 6 -> 1))

assert(List(5, 6).zipAll(List('A'), 9, 'Z') == List(5 -> 'A', 6 -> 'Z'))

assert(List(5).zipAll(List('A', 'B'), 1, 'Z') == List(5 -> 'A', 1 -> 'B'))
``````

# Scala Algorithms: The most comprehensive library of algorithms in standard pure-functional Scala

## How our 100 algorithms look

1. A description/goal of the algorithm.
2. An explanation with both Scala and logical parts.
3. A proof or a derivation, where appropriate.
4. Links to Scala concepts used in this specific algorithm, also unit-tested.
5. An implementation in pure-functional immutable Scala, with efficiency in mind (for most algorithms, this is for paid subscribers only).
6. Unit tests, with a button to run them immediately in our in-browser IDE.

### Study our 100 Scala Algorithms: 6 fully free, 100 published & 0 upcoming

Fully unit-tested, with explanations and relevant concepts; new algorithms published about once a week.

### Explore the 22 most useful Scala concepts

To save you going through various tutorials, we cherry-picked the most useful Scala concepts in a consistent form.

## Subscribe to Scala Algorithms

Maximize your Scala with disciplined and consistently unit-tested solutions to 100+ algorithms.

Use it from improving your day-to-day data structures and Scala; all the way to interviewing.