打印从根到叶子节点的所有路径n元树

4
我正在尝试打印从根到所有叶子节点的n叉树路径。这段代码打印了到叶子节点的路径,但也打印了子路径。
例如,假设有一条路径是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
我不懂Matlab,所以你能解释一下labels(output.edges{e}(2)+1)中的+1背后的逻辑吗?表面上看起来,你似乎在查看与边无关的节点的标签,或者你是否有一些固定的节点编号系统? - trincot
1
如果您在问题中加上了“matlab”标签,它可能会得到更多的关注,我现在已经添加了。 - trincot
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接