aspose file tools*
The moose likes Beginning Java and the fly likes recursive tree Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "recursive tree" Watch "recursive tree" New topic
Author

recursive tree

Pat Peg
Ranch Hand

Joined: Feb 04, 2005
Posts: 194
I have a group of object, each object knows it’s ID and it’s parent ID (if it has one).

I have a method call that will return a List of objects based on a parent ID.

public List<MyRecords> getChildRecords(Long recordID)…

what I need to do is create a method that will return all the objects after I have gotten the root object. I would like to do this recursively.

And in case you are wondering, no this isn’t a class assignment or anything. It is just that looking at the problem I am thinking it would probably be a good example of where to do recursion but I just can’t wrap my head around it right now.

Thanks
Pat Peg
Ranch Hand

Joined: Feb 04, 2005
Posts: 194
and to give an example of what the data might look like


sorry if the formatting got lost....
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11406
    
  16

I wrapped your data in code tags. while it's not actually code, doing that will preserve the formatting.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19718
    
  20

The algorithm as I've described before:
1) use a Map<ID,Node> to first store the nodes unlinked to their parent nodes. They will need a parent ID though.
2) iterate over the nodes, lookup the parent node in the map using the parent ID, and link together.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: recursive tree