[英]How to find the sum of all nodes in a tree
節點是這樣定義的:
一個節點是一個對象
- 值:數字
- 孩子:節點列表
class Node:
def __init__(self, key, childnodes):
self.key = key
self.childnodes = childnodes
def __repr__(self):
return f'Node({self.key!r}, {self.childnodes!r})
testTree = Node(1, [Node(2, []), Node(3, [Node(4, [Node(5, []), Node(6, [Node(7, [])])])])])
我一直在嘗試的代碼是:
def sum_of_nodes(root):
if root is None:
return 0
return root.key + sum_of_nodes(root.childnodes[0]) + sum_of_nodes(root.childnodes[1])
但是我收到錯誤:
Traceback (most recent call last): File "D: /Documents/project1.py", line 170, in <module> print (f'sum_of_nodes (exampleTree) => {sum_of_nodes (exampleTree)}') # 28 File "D: /Documents/project1.py", line 81, in sum_of_nodes return root.value + sum_of_nodes (root.subnodes[0]) + sum_of_nodes (root.subnodes[1]) File "D: /Documents/project1.py", line 81, in sum_of_nodes return root.value + sum_of_nodes (root.subnodes[0]) + sum_of_nodes (root.subnodes[1]) IndexError: list index out of range
您可以使用for
循環,而不是使用索引來查找子節點:
def sum_of_nodes(root):
return root.key+sum(sum_of_nodes(i) for i in root.childnodes)
print(sum_of_nodes(testTree))
輸出:
28
您可以使用遞歸方法對節點求和。 遞歸調用僅在節點不是 None 時發生。 添加當前節點的值,然后檢查它是否有任何子節點。 如果是,則迭代每個子節點,調用遞歸方法,並將結果final_sum
添加到當前節點的final_sum
。 每個函數調用都有自己的final_sum
值,但根節點上的函數調用將在所有子節點上累積final_sum
。
def get_sum(node):
final_sum = 0
if node is not None:
final_sum += node.key
if node.childnodes is not None:
for child in node.childnodes:
final_sum += get_sum(child)
return final_sum
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.