2015-01-27 4 views
0

Я видел anwser здесь, но у меня нет объекта Empty, и у меня есть лист не просто everthing в Node: case class Node (val e: Int, слева: BinaryTree, справа: BinaryTree).Scala sum binary Tree

У меня проблема с добавлением Листа в качестве параметра в этой сумме def.

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) 
} 


} 

ответ

1

Если я понимаю, что вы хотите сделать что-то вроде

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

вы я просто достичь этого 5 минут назад: D Но спасибо за anwser –

0

Может быть:

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