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