「ツリー内のすべてのパスを列挙する」という質問への回答に触発されて、私は適応バージョンを書きました(ルート化されていないパスは必要ありません):
def paths(tree):
#Helper function
#receives a tree and
#returns all paths that have this node as root
if not tree:
return []
else: #tree is a node
root = tree.ID
rooted_paths = [[root]]
for subtree in tree.nextDest:
useable = paths(subtree)
for path in useable:
rooted_paths.append([root]+path)
return rooted_paths
ここで、「ツリー」オブジェクトには、各ノードに関連付けられた番号 (tree.number) があります。私はこのように見えます:
A,2
/ \
B,5 C,4
| / \
D,1 E,4 F,3
生成された各パスの合計を知るために、パスを 0 値で初期化し、パスのすべての tree.numbers を合計したいと思います。
A-B-D: 8
A-C-E: 10
A-C-F: 9
この結果を得るには、コードをどのように変更すればよいですか? 私はそれを行う方法を見ていません。