我有一棵可以有多个根节点的树。该节点定义为:
case class Node[A] ( id: Int, data: A, var children: Option[Seq[Node[A]]],
var parent: Option[Node[A]] )
其中id标识节点,数据是与节点相关的信息,子节点是节点序列,父节点指向父节点。
树类如下:
case class Tree[A] ( var nodes: Option[Seq[Node[A]]] ) {
def searchParent (searchId: Int): Option[Node[A]] = {
nodes match {
case Some(nodes) => {
for ( node <- nodes ) {
val parent = searchParent2(node,searchId)
parent match {
case Some(p) => {
parent
}
case None => None
}
}
None
}
case None => None
}
}
def searchParent2 (node: Node[A], searchId: Int): Option[Node[A]] = {
node.children match {
case Some(nodes2) => {
for ( node2 <- nodes2 ) {
if (node2.id == searchId)
Some(node2)
else
searchParent2(node2,searchId)
}
None
}
case None => None
}
}
}
问题是,当我根据其id搜索节点时,我总是得到None。这段代码出了什么问题?