【问题标题】:Scala sum binary TreeScala求和二叉树
【发布时间】: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


    【解决方案1】:

    如果我理解你想要做的事情是这样的

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

    【讨论】:

    • 是的,我刚刚在 5 分钟前实现了这一点:D 但是感谢 anwser
    【解决方案2】:

    可能是:

      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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多