Hello, I have a Tree structure with custom TreeNode nodes. The structure of TreeNode is:
private int level;
private String label = null;
private String data = null;
private TreeNode parent = null;
private Vector <TreeNode> children = null;

I should find each unique path from root to all leaves of the tree. Is there any suggestion about this? I tried to do it with a stack but there was no result.

Thanks in advance. :)

8 Years
Discussion Span
Last Post by kakakon

For any node the possible paths consist of the possible paths for all its children, but with the current node inserted at the front of each path. In pseudo-code it kinda looks like this:

public CollectionOfPaths getPaths() {
   CollectionOfPaths cp = new empty collection of paths
   // (where a "path" is an ordered list of nodes)
   if there are no child nodes {
      return a new path consisting of just this node
   for each child node {
      CollectionOfPaths ccp = child.getPaths()
      for each path in ccp {
         add this node to start of the path
         add the path to cp
   return cp

So call this on the top node and it will recurse all the way down to every leaf and return all the paths.


thank you for your reply.
i used a queue to find which nodes are leaves (don't have any children) an then make an array[level], where level is the depth of each leaf in tree structure. then i put at array[level-1] the leave and take with the getParent() the anchestors to fill the previous positions of the vector.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.