我在这里看到了anwser,但是我没有Object Empty,我不仅仅在这样的节点中使用了叶子: case class Node(val e:Int,left:BinaryTree,right:BinaryTree)。
我在这个def sums中添加Leaf作为param有问题。
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)
}
}
答案 0 :(得分:1)
如果我明白你想做什么就像是
case Leaf(v) :: rs => sums(xs, acc+v)
答案 1 :(得分: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