Created
July 24, 2011 14:57
-
-
Save kmizu/1102700 to your computer and use it in GitHub Desktop.
Create Iterator which traverse binary tree nodes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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