Help coderanch get a
new server
by contributing to the fundraiser
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Ron McLeod
• Paul Clapham
• Devaka Cooray
• Liutauras Vilda
Sheriffs:
• Jeanne Boyarsky
• paul wheaton
• Henry Wong
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Tim Moores
• Carey Brown
• Mikalai Zaikin
Bartenders:
• Lou Hamers
• Piet Souris
• Frits Walraven

# Recursive function - to get Children(might be parents too) of parents - URGENT PLEAS

Greenhorn
Posts: 20
• Number of slices to send:
Optional 'thank-you' note:
Hi
Can anyone of you help me with the source code for this recursion problem, I will truely appreciate this has been haunting me for some days now.
The problem is, I have 2 fields
Node_id ParentNode
B A
C A
D B
E B
F B
G C
H E
I E
And the list could go on indefinitely. What I want is the output which accepts a Parent_nod (Example A) and lists all the children
{B,C,D,E,F,G,H,I) preferable output will be (B,D,E,H,I,F,C,G List a parent and the childs of that parents)
I know I can solve this with a recursive function but an stuck now

author and iconoclast
Posts: 24207
46
• Number of slices to send:
Optional 'thank-you' note:
What have you tried so far? Show us what you've got.

Greenhorn
Posts: 17
• Number of slices to send:
Optional 'thank-you' note:
My two cents worth
Well obviously the terminating condition is when the node is a leaf and doesn't have any children.
ArrayList (??) nodes; // just as an example
printChildren(Node parent)
{
for(int i = 0; i != nodes.size(); i++)
{
Node node = (Node)nodes.get(i);
if(node.parent_id.equals(parent.node_id))
{
System.out.println(node.node_id);
printChildren(node);
}
}
}

(instanceof Sidekick)
Posts: 8791
• Number of slices to send:
Optional 'thank-you' note:
I'd expect to see something like this:

This terminates when there are no children. If you're loading your tree of nodes from a text file as shown, make sure you don't say A->B and B->A or it will run forever!
To make it print as an outline, with cool indentation, keep track of recursion depth. Pass a level of 0 when first calling printNodeAndChildren, then pass level+1 when calling itself recursively. Print that many spaces in front of the value.