问题描述
我有一个特征sealed trait Tree[+T] extends Product with Serializable
final case object Leaf extends Tree[nothing]
final case class Node[+T](value: T,left: Tree[T],right: Tree[T]) extends Tree[T]
,定义如下:
val x = Node(1,Node(2,Leaf,Leaf),Node(3,Node(4,Leaf)))
val paths = findpaths(x)
paths will have the list of lists = List((1,2),List(1,3,4))
我是FP和Scala的新手,我想知道什么是检索给定树从根开始的所有可能路径的最佳和最佳方法。 例如对于树:
{{1}}
当然,树会更大。
解决方法
五个可能的分支。
def allPaths[A](tree:Tree[A]):List[List[A]] = tree match {
case Leaf => Nil
case Node(v,Leaf,Leaf) => List(v::Nil)
case Node(v,rgt) => allPaths(rgt).map(v::_)
case Node(v,lft,Leaf) => allPaths(lft).map(v::_)
case Node(v,rgt) => (allPaths(lft) ++ allPaths(rgt)).map(v::_)
}
测试:
val x = Node(1,Node(2,Leaf),Node(3,Node(4,Leaf)))
allPaths(x)
//res0: List[List[Int]] = List(List(1,2),List(1,3,4))