Check out Manning's Countdown to 2014. Use discount code crdotd14 all month for 50% off every deal.
Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

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

peter brews
Greenhorn

Joined: Feb 11, 2002
Posts: 20
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
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24148

27

What have you tried so far? Show us what you've got.

Julie de Wet
Greenhorn

Joined: Apr 04, 2004
Posts: 17
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);
}
}
}
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi

Don't get me started about those stupid light bulbs.

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