# Scala algorithm: Check a binary tree is a search tree

Published

## Algorithm goal

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!

## Explanation

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

1. ### Lazy List

The 'LazyList' type (previously known as 'Stream' in Scala) is used to describe a potentially infinite list that evaluates only when necessary ('lazily').

2. ### Option Type

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!

``````assert(Option(1).flatMap(x => Option(x + 2)) == Option(3))

assert(Option(1).flatMap(x => None) == None)
``````
3. ### Ordering

In Scala, the 'Ordering' type is a 'type class' that contains methods to determine an ordering of specific types.

``````assert(List(3, 2, 1).sorted == List(1, 2, 3))

assert(List(3, 2, 1).sorted(Ordering[Int].reverse) == List(3, 2, 1))

assert(Ordering[Int].lt(1, 2))

assert(!Ordering[Int].lt(2, 1))
``````
4. ### Sliding / Sliding Window

Get fixed-length sliding sub-sequences (sliding windows) from another sequence

5. ### Type Class

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:

``````import Ordering.Implicits._

type CommonType = (Int, String, Option[String])

val a: CommonType = (1, "X", None)

val b: CommonType = (2, "A", Some("B"))

assert(a < b, "We can order tuples using Scala-provided type classes")
``````

# 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

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