Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created July 24, 2011 14:57
Show Gist options
  • Save kmizu/1102700 to your computer and use it in GitHub Desktop.
Save kmizu/1102700 to your computer and use it in GitHub Desktop.
Create Iterator which traverse binary tree nodes.
object BinTreeIterator {
sealed trait Tree
case class Node(v: Int, l: Tree, r: Tree) extends Tree
case object Leaf extends Tree
def toIterator(node: Tree): Iterator[Int] = {
def toStream(n: Tree): Stream[Int] = n match {
case Node(v, l, r) => v #:: toStream(l) #::: toStream(r)
case Leaf => Stream.empty
}
toStream(node).iterator
}
def main(args: Array[String]) {
var it = toIterator(Node(1, Node(2, Leaf, Leaf), Node(3, Leaf, Leaf)))
for(e <- it) {
println(e)
}
// val e: Int = 0
// while(it.hasNext) {
// println(it.next) //こっちももちろん動く
// }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment