Win a copy of Succeeding with AI this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Junilu Lacar
Sheriffs:
  • Tim Cooke
  • Jeanne Boyarsky
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • fred rosenberger
  • Frits Walraven

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

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Please help
 
author and iconoclast
Posts: 24203
43
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What have you tried so far? Show us what you've got.
 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
What I don't understand is how they changed the earth's orbit to fit the metric calendar. Tiny ad:
Try Free Java/.NET Libraries for Word Excel PowerPoint and PDF
htttp://www.e-iceblue.com/free-apis.html
    Bookmark Topic Watch Topic
  • New Topic