打印从根到叶子n-ary树的所有路径

时间:2017-08-21 03:19:47

标签: algorithm graph tree depth-first-search

我正在尝试打印从n-ary树中的所有路径到所有叶子的路径。此代码打印叶子的路径,但它也打印子路径。

例如,假设一条路径是1-5-7-11。它打印1-5-7-11,但它也打印1-5-7,1-5,等等。

如何避免此打印子路径?

这是我在matlab中的代码

由于

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

1 个答案:

答案 0 :(得分:0)

让我们将问题分为两部分。

1。查找树中的所有叶节点

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。给定叶子,找到其到根的路径

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