Skip to content

Instantly share code, notes, and snippets.

@giovannicandido
Created February 25, 2015 17:10
Show Gist options
  • Save giovannicandido/9e4d14c1ae4ff71e7eed to your computer and use it in GitHub Desktop.
Save giovannicandido/9e4d14c1ae4ff71e7eed to your computer and use it in GitHub Desktop.
Busca recusiva em grafo binario
object Main extends App {
case class Vertice(valor: Int, esquerda: Option[Vertice], direita: Option[Vertice]) {
override def toString = valor.toString
}
val v1 = Vertice(10,None,None)
val v3 = Vertice(30,None,None)
val v2 = Vertice(5,Some(v3),None)
val root = Vertice(3,Some(v1), Some(v2))
def imprimeGrafo(vertice: Vertice): Unit = {
def recurse(v: Option[Vertice]): Unit = {
if(v.isEmpty){
println("folha")
}else {
println(v.get.valor)
recurse(v.get.esquerda)
recurse(v.get.direita)
}
}
recurse(Some(vertice))
}
def localiza(vertice: Option[Vertice], valor: Int): Boolean = {
println(s"in vertice $vertice")
if(vertice.isEmpty)
false
else if(vertice.get.valor == valor) true
else {
localiza(vertice.get.esquerda, valor) || localiza(vertice.get.direita, valor)
}
}
imprimeGrafo(root)
println("=== Localizando 30")
println(localiza(Some(root),30))
println("=== Localizando 10")
println(localiza(Some(root), 10))
println("=== Localizando -1")
println(localiza(Some(root), -1))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment