4

I am trying to print all paths from root to all leaves in n-ary tree. This code prints the paths to the leaves, but it also prints subpaths too.

For example, let's say one path is 1-5-7-11. It prints 1-5-7-11, but it also prints 1-5-7, 1-5, so on.

How can I avoid this printing subpaths ?

Here is my code in matlab

Thanks

stack=java.util.Stack();
stack.push(0);
CP = [];
Q = [];
labels = ones(1,size(output.vertices,2));    
while ~stack.empty()      
    x = stack.peek();
    for e = 1:size(output.edges,2)
        if output.edges{e}(1) == x && labels(output.edges{e}(2)+1) == 1
            w = output.edges{e}(2);
            stack.push(w);
            CP = union(CP,w);  
            break                
        end        
    end   

    if e == size(output.edges,2)
         Q = [];
         for v=1:size(CP,2)
            Q = union(Q,CP(v));
         end
        disp(Q)
        stack.pop();
        labels(x+1) = 0;            
        CP = CP(find(CP~=x));
    end

end
trincot
  • 317,000
  • 35
  • 244
  • 286
eds
  • 41
  • 2
  • 1
    I don't know matlab, so can you explain the logic behind the `+1` in `labels(output.edges{e}(2)+1)`? Naively it looks like you are looking at the label of a node that has nothing to do with the edge, or do you have some fixed numbering system for the nodes? – trincot Jun 25 '20 at 11:25
  • 1
    This question would have received more attention if you would have tagged it with `matlab`, which I am adding now.. – trincot Jun 25 '20 at 11:25

1 Answers1

0

Let's split the problem in two parts.

1. Find all leaf-nodes in a tree

input: Tree (T), with nodes N  
output: subset of N (L), such that each node in L is a leaf

initialize an empty stack
push the root node on the stack
while the stack is not empty
do
    pop a node from the stack, call it M
    if M is a leaf, add it to L
    if M is not a leaf, push all its children on the stack
done

2. Given a leaf, find its path to the root

input: leaf node L
output: a path from L to R, with R being the root of the tree

initialize an empty list (P)
while L is not the root of the tree
do
    append L to the list
    L = parent of L
done
return P
Joris Schellekens
  • 8,483
  • 2
  • 23
  • 54