在scala中Map“加权树”

tgabmvqs  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(356)

问题是:

从我已经完成的这个“加权树”特征中,只剩下一个片段,即以下函数:
编写一个函数,它接收一个“weightedtree”作为输入,并返回一个“map[char,string]:对于“weightedtree”的“leafs”中的每个字符,我们编写它指向特定字符的方式(向左表示“0”,向右表示“1”),如下所示:
示例:inner(inner(leaf('a',4),5,leaf('c',1)),10,leaf('b',5))-->map('a'->“00”,'b'->“1”,'c'->“01”)

代码:

trait WeightedTree {
  val weight: Int
}
case class Leaf(c: Char, weight: Int) extends WeightedTree
case class Inner(left: WeightedTree, weight: Int, right: WeightedTree) extends WeightedTree

object CodeCreator extends App {
  def treeToMap( codeTree: WeightedTree ): Map[Char, String] = ???
}
gj3fmq9x

gj3fmq9x1#

朋友们帮了忙,我们把这个放在一起,它成功了!

def treeToMap(codeTree: WeightedTree): Map[Char, String] = {

  def InnerLoop(innerTree: WeightedTree, path: String): Map[Char, String] = innerTree 
    match {

      case Leaf(ch, c) => Map(ch -> path)
      case Inner(left, _: Int, right) =>

        InnerLoop(left, path + "0") ++ InnerLoop(right, path + "1")
    }

  InnerLoop(codeTree, "")
}

相关问题