【问题标题】:print all paths from root to leaves n-ary tree打印从根到叶子的所有路径
【发布时间】:2018-01-29 01:02:01
【问题描述】:

我正在尝试打印从根到 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

【问题讨论】:

  • 我不懂matlab,能解释一下labels(output.edges{e}(2)+1)+1背后的逻辑吗?天真地看起来您正在查看与边缘无关的节点的标签,或者您是否有一些固定的节点编号系统?
  • 如果您将其标记为matlab,这个问题会受到更多关注,我现在正在添加它..

标签: algorithm matlab graph tree depth-first-search


【解决方案1】:

让我们把问题分成两部分。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    相关资源
    最近更新 更多