我将树定义为
sealed trait Tree[+A]
case class Leaf[A](value: A) extends Tree[A]
case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]
我想要一个函数来计算树中的节点数和一个计算叶子数的函数
(我编写了一个函数来计算叶子的数量,但我不满意我正在使用的方法。我想要一个更“实用”的实现)。
val t1 = Branch(
Branch(
Leaf(12),
Branch(
Leaf(3),
Leaf(4))),
Leaf(8)) //> t1 : trees.Branch[Int] = Branch(Branch(Leaf(12),Branch(Leaf(3),Leaf(4))),Le
//| af(8))
def n_nodes(t:Tree[Int]):Int = {
var s = 0
def n_nodesAcc(t:Tree[Int]):Unit = {
t match {
case Branch(left, right) =>{
n_nodesAcc(left)
n_nodesAcc(right )
}
case Leaf(v) => {s = s+ 1}
}
}
n_nodesAcc(t)
s
} //> n_nodes: (t: trees.Tree[Int])Int
n_nodes(t1) //> res0: Int = 4
(这是一项练习)
答案 0 :(得分:2)
您可以编写一个递归方法来计算叶子:
def countLeaves[A](tree: Tree[A]): Int = tree match {
case l:Leaf[A] => 1
case b:Branch[A] => countLeaves(b.left) + countLeaves(b.right)
}
或计算所有节点:
def countNodes[A](tree: Tree[A]): Int = tree match {
case l:Leaf[A] => 1
case b:Branch[A] => 1 + countLeaves(b.left) + countLeaves(b.right)
}
您也可以编写一个类似的方法来获取所有叶子,并且您可以更灵活地在以后执行不同的功能:
def getLeaves[A](tree: Tree[A]): Seq[Leaf[A]] = tree match {
case l:Leaf[A] => Seq(l)
case b:Branch[A] => getLeaves(b.left) ++ getLeaves(b.right)
}
然后用getLeaves(t1).length
计算。或者,类似地,获取所有节点:
def getNodes[A](tree: Tree[A]): Seq[Tree[A]] = tree match {
case l:Leaf[A] => Seq(l)
case b:Branch[A] => Seq(b) ++ getNodes(b.left) ++ getNodes(b.right)
}