I have the following object structure:
case class Node(id:Int,children:List[Node])
Example:
NodeA
id: 1
children:[
NodeA1:
id: 2
children:
NodeA11
...
]
NodeB1:
id: 3
children:[]
NodeC1:
id: 17
children: [
NodeC11:
id:11
children:[
NodeC111:
id: 19
children: []
]
]
...
I would like to create a recursive looping to get the Node that has a specific Id but i'm stuck in how to keep running the fuction if the iD isn't found and the object has any object on children list. My function only works to get the first node (ex.: Id = 1).
Here is what i'm trying to do:
def getNode(id:Int, node:Node) : Node = {
var result:Node = null
if(node.id == id){
return node
} else if(node.children.size > 0 ){
for(children <- node.children){
result = getNode(id, children)
if(result.id == id){
return result
}
}
}
return result
}
nullwhen nothing is found?