[英]print all paths from root to leaves n-ary tree
我正在尝试打印 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.