Scala 求和二叉树
Scala sum binary Tree
我在这里看到了 anwser,但我没有空对象,而且我在 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)
}
}
如果我理解你想做的是
case Leaf(v) :: rs => sums(xs, acc+v)
可能是:
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
我在这里看到了 anwser,但我没有空对象,而且我在 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)
}
}
如果我理解你想做的是
case Leaf(v) :: rs => sums(xs, acc+v)
可能是:
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