Skip to content

Instantly share code, notes, and snippets.

@dholbrook
Created June 21, 2012 17:59
Show Gist options
  • Save dholbrook/2967371 to your computer and use it in GitHub Desktop.
Save dholbrook/2967371 to your computer and use it in GitHub Desktop.
Scala binary tree
abstract class Tree[+A] {
def value: Option[A] = this match {
case n: Node[A] => Some(n.v)
case l: Leaf[A] => Some(l.v)
case Empty => None
}
def left: Option[Tree[A]] = this match {
case n: Node[A] => Some(n.l)
case l: Leaf[A] => None
case Empty => None
}
def right: Option[Tree[A]] = this match {
case n: Node[A] => Some(n.r)
case l: Leaf[A] => None
case Empty => None
}
def count: Int = {
def loop(t: Tree[_]): Int = t match {
case n: Node[_] => Seq(loop(n.left.get), loop(n.right.get)).sum + 1
case l: Leaf[_] => 1
case Empty => 0
}
loop(this)
}
}
case class Node[A](v: A, l: Tree[A], r: Tree[A]) extends Tree
case class Leaf[A](v: A) extends Tree
case object Empty extends Tree[Nothing]
object Run extends App {
val t: Tree[Symbol] = Node('A, Node('B, Leaf('D), Leaf('E)), Node('C, Empty, Node('F, Leaf('G), Empty)))
println("tree: " + t)
//print the value of b node navigating from root
for {
b <- t.left
value <- b.value
} println("B node: " + value)
//print the value of e node navigating from root
for {
b <- t.left
e <- b.right
value <- e.value
} println("E node: " + value)
//no println() is executed for empty node chain
for {
b <- t.left
e <- b.right
x <- e.right //no node here
value <- x.value
} println("X node SHOUL NOT PRINT!: " + value)
println("count " + t.count)
/****** output *********
tree: Node('A,Node('B,Leaf('D),Leaf('E)),Node('C,Empty,Node('F,Leaf('G),Empty)))
B node: 'B
E node: 'E
count 7
*************************/
}
@NightRa
Copy link

NightRa commented Apr 15, 2013

Beautiful.

@DeaconDesperado
Copy link

🎉

@skissh
Copy link

skissh commented Feb 18, 2016

Would some one please show my how to use foldLoop or fold to return a modified tree?

@derekennui
Copy link

Good job!

@aesguerra
Copy link

Exquisite.

@macakmujo
Copy link

very cool, nice work :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment