0

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 Answers 2

1

If I understand what you want to do is something like

case Leaf(v) :: rs => sums(xs, acc+v)
Sign up to request clarification or add additional context in comments.

1 Comment

ye i just achieve this 5 minutes ago :D But thanks for anwser
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.