Looking for help with my tree structure. I am trying to retrieve all ancestors of a specific node in the tree, where each node can have multiple children and each child can also be a parent.
https://i.sstatic.net/cPqSM.png
Below is the code I've written to achieve this, but it consistently returns undefined. Any suggestions or advice would be greatly appreciated.
getAncestors(nodeId: number, ancestors: number[] = []): number[] {
if (this.nodeId === nodeId) {
return ancestors;
}
if (this.children.length > 0) {
ancestors.push(this.nodeId);
}
for (const child of this.children) {
child.getAncestors(nodeId, ancestors);
}
return ancestors;
}