斯卡拉和二进制树

时间:2015-01-27 13:13:12

标签: scala binary-tree

我在这里看到了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)
}


}

2 个答案:

答案 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