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. :)

You need a recursive solution

What should I do within the recursive?

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.