# Scala algorithm: Find height of binary tree

Published

## Algorithm goal

A binary tree is a structure that has a value, and 2 optional children. The height of a binary tree is spans the longest chain from the start/root node to a leaf node.

## Test cases in Scala

``````assert(BinaryTree.Empty[Int]().height == 0)
assert(BinaryTree.of[Int](1).height == 1)
assert(BinaryTree.of(1).copy(right = BinaryTree.of(2)).height == 2)
assert(
BinaryTree
.of(2)
.copy(left = BinaryTree.of(1), right = BinaryTree.of(3))
.height == 2
)
assert(
BinaryTree
.of(2)
.copy(
left = BinaryTree.of(1),
right = BinaryTree.of(3).copy(right = BinaryTree.of(0))
)
.height == 3
)
``````

## Algorithm in Scala

22 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!

## Explanation

We look at 2 implementations: the most straight forward implementation uses a recursive approach, where compute tha maximum height of 2 child nodes, and add 1 to that. The issue with this is that is is not stack-safe (Stack Safety), however we can get past that by using an iterative approach, where we count the maximum number of iterations that we can perform of finding children of children. This is done with Scala's `.iterate` method. (this is Â© from www.scala-algorithms.com)

## Scala concepts & Hints

1. ### State machine

A state machine is the use of `sealed trait` to represent all the possible states (and transitions) of a 'machine' in a hierarchical form.

# 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.