【发布时间】:2017-01-23 15:57:42
【问题描述】:
我对 List[(nodeID, parentID)] -> 树结构有问题
val tree: List[(Int, Int)] = List((1,0),(2,0),(3,0),(4,1),(5,4),(6,2),(7,6))
我的树案例类
case class Tree(value: Int, subTree: List[Tree])
我的代码
def DFS(tree: List[(Int, Int)], id: Int): List[Tree] = {
if(tree.isEmpty) Nil
else List(Tree(id, tree.filter(x => x._2 == id).flatMap(x => DFS(tree, x._1))))}
结果
List(Tree(0,List(Tree(1,List(Tree(4,List(Tree(5,List()))))), Tree(2,List(Tree(6,List(Tree(7,List()))))), Tree(3,List()))))
我发现列表中大数据的堆栈溢出
所以我想把它改成尾递归、映射或折叠
【问题讨论】:
-
确保你的递归代码是尾递归的,否则会导致大输入时堆栈溢出
-
请改成尾递归调用,我不知道该怎么做
-
Tree的value属性是ID,对吧? -
是的,一个值为ID
标签: scala