【发布时间】:2015-01-27 13:13:11
【问题描述】:
我在这里看到了 anwser,但我没有 Object Empty,而且我的叶子不仅仅是 Node 中的任何东西,像这样: case class Node ( val e : Int ,left : BinaryTree, right : BinaryTree)。
我在这个 def sums 中添加 Leaf 作为参数时遇到问题。
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)
}
}
【问题讨论】:
标签: scala binary-tree