# 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

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

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

### Explore the 21 most useful Scala concepts

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

## Register now (free)

Register with GitHub

This gives you access to free test cases & hints for all our 89 published algorithms as well as our installation-free Scala IDE.

You can then choose to subscribe to "Scala Algorithms Unlimited", which gets you access to every current and upcoming algorithm solution. We use Stripe so your data is safe.

We will e-mail you at most once per week with new algorithms and relevant content.
Your data is protected and unsubscribing is straightforward. 