A binary tree is a tree that can only have at most 2 children. A search tree is a tree in which all the children to the left of the node are < than the value of this node, and all items of the right are >=, and this property also applies to their children nodes as well.
This property enables very fast lookups (hence the name a search tree) due to the ordering guarantees.
Test cases in Scala
assert(BinaryTree.of[Int](1).isSearchTree) assert(BinaryTree.of(1).withRight(2).isSearchTree) assert(!BinaryTree.of(2).withRight(1).isSearchTree) assert(BinaryTree.of(2).withLeft(1).withRight(3).isSearchTree) assert( !BinaryTree.of(2).withLeft(1).withRight(3, _.withRight(0)).isSearchTree ) assert( BinaryTree.of(2).withLeft(1).withRight(3, _.withRight(5)).isSearchTree )
Algorithm in Scala
29 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
A common mistake in implementing this algorithm is to think that comparing a node's value with the value of its direct child is enough.
In fact, one has to ensure that the property applies to all the children. While it is possible to verify this by traversing the tree top-down, in fact a better approach is to perform an in-order traversal of the tree and check that it is sorted. In this algorithm, we do exactly that using LazyLists and implicit classes provided by Scala. (this is © from www.scala-algorithms.com)
Scala concepts & Hints
The 'LazyList' type (previously known as 'Stream' in Scala) is used to describe a potentially infinite list that evaluates only when necessary ('lazily').
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!
In Scala, the 'Ordering' type is a 'type class' that contains methods to determine an ordering of specific types.
Sliding / Sliding Window
Get fixed-length sliding sub-sequences (sliding windows) from another sequence
Type classes are one of Scala's most important super-powers: they enable you to add new behaviour to existing classes, without modifying those classes. In many languages, to add a behaviour to a class, you would typically extend it with an interface, and then implement methods against this interface.This, however, does not scale: especially when you have older libraries, you would be forced to make them depend on a new interface, and have to re-build everything.
Type classes are used heavily in Apple's SwiftUI as "extensions" to enable powerful abstraction capabilities.
Type classes enable you to do things like this: