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

标签 algorithm matlab graph tree depth-first-search

我正在尝试打印 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. 查找树中的所有叶节点

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

关于algorithm - 打印从根到叶子的 n 叉树的所有路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45788885/

相关文章:

java - 动态规划 : Bits Array Java

c++ - 错误 "Disallowed system call: SYS_kill",因为我尝试从字符串中删除所有连续的重复元素

java - 从 Java 中的给定树中检索所有节点

matlab - SVD 在 Matlab 和 OpenCV 中计算不同的结果

MATLAB 将向量元素分配给单个变量的最简单方法

algorithm - 在不使用数组/向量的情况下计算数字序列的模式

matlab - matlab 有 matlabrc 文件吗?

graph - 我的 TreeMap 的 Arangodb 自定义过滤器/访问者

java - 5x5 数字网格中的广度优先和深度优先搜索算法

algorithm - 如何找到不会造成循环依赖的子包