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
Algorithm in Scala
22 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
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
A state machine is the use of `sealed trait` to represent all the possible states (and transitions) of a 'machine' in a hierarchical form.