0
votes

I saw anwser here but i dont have Object Empty and i have leaf not just everthing in Node like this : case class Node ( val e : Int ,left : BinaryTree, right : BinaryTree).

I have problem with adding Leaf as param in this def sums.

import scala.annotation.tailrec
 /**
 * @author emil
 */
 class tree {


 }


 sealed abstract class BinaryTree
 case class Node (left : BinaryTree, right : BinaryTree) extends BinaryTree
 case class Leaf (value : Int) extends BinaryTree


 object Main {
   def main(args : Array[String]) {
     val tree = Node(Node(Leaf(1),Leaf(3)), Node(Leaf(5),Leaf(7)));

     println(tree)

  sum(tree)

   }
  def sum(bin: BinaryTree) = {
  def sums(trees: List[BinaryTree], acc: Int): Int = trees match {
    case Nil => acc
    case Node(l, r) :: rs => sums(l :: r :: rs,  acc)
  }

  sums(List(bin),0)
}


}
2

2 Answers

1
votes

If I understand what you want to do is something like

case Leaf(v) :: rs => sums(xs, acc+v)
0
votes

May be:

  def sum(bin: BinaryTree) = {
    def sums(t: BinaryTree): Int = t match {
      case Leaf(v)    => v
      case Node(l, r) => sums(l) + sums(r)
    }

    sums(bin)
  }

  val res = sum(tree)
  println(res) // 16