I have been scratching my head to find a solution to this problem. I am not very good with data structures and it seems that my brain melts a little whenever I have to do anything to do with trees.
Suppose we have a Node():
Node(name: String, children: List<Node>?)
And we have a tree made up of these nodes:
var node6 = Node("6", null)
var node5 = Node("5", null)
var node4 = Node("4", null)
var node3 = Node("3", listOf(node5, node6))
var node2 = Node("2", null)
var node1 = Node("1", listOf(node2, node3, node4))
What approach could I take to find the path (stored) to node6 while only having the root available?
Thank you kindly for any advice you could offer!
Solution as per JayC667's guidance:
fun recursiveCheck(
nodeA: Node,
nodePath: Stack<Node>,
nodeToFind: String
) : Boolean {
// Push param node to stack
nodePath.push(nodeA)
// Check param node
if(nodeA.name == nodeToFind) {
return true
}
if(nodeA.children != null) {
// Iterate over all children using recursive check
for(child in nodeA.children!!) {
// child found as param node
if(recursiveCheck(child, nodePath, nodeToFind)) return true
}
}
// Did not find node, popping off stack
nodePath.pop()
return false
}