gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:28:45 33 4
gpt4 key购买 nike

我正在尝试打印 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com