Bohtvaroh

Blogger - Folding tree - 1

Jun 5th, 2012
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.62 KB | None | 0 0
  1. sealed trait Tree[E]
  2. case class Empty[E]() extends Tree[E]
  3. case class Node[E](el: E, left: Tree[E], right: Tree[E]) extends Tree[E]
  4.  
  5. def toListSimple[A](tree: Tree[A]): List[A] = tree match {
  6.   case Node(el, left, right) => toListSimple(left) ::: (el :: toListSimple(right))
  7.   case Empty() => Nil
  8. }
  9.  
  10. def toList[A](tree: Tree[A]): List[A] = {
  11.   def toListBuffer(tree: Tree[A], b: ListBuffer[A]): ListBuffer[A] = tree match {
  12.     case Node(el, left, right) => {
  13.       toListBuffer(left, b)
  14.       b += el
  15.       toListBuffer(right, b)
  16.     }
  17.     case Empty() => b
  18.   }
  19.   toListBuffer(tree, new ListBuffer[A]).toList
  20. }
Advertisement
Add Comment
Please, Sign In to add comment