简体   繁体   中英

How to find the sum of all nodes in a tree

This is how the node is defined:
A Node is an object
- Value: Number
- Children: List of Nodes

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, [])])])])])

The code I've been trying is:

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])

However I get the error:

 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

Instead of using indexing to lookup the child nodes, you can use a for loop:

def sum_of_nodes(root):
  return root.key+sum(sum_of_nodes(i) for i in root.childnodes)

print(sum_of_nodes(testTree))

Output:

28

You can use a recursive approach to sum the nodes. The recursive call only happens if the node is not None. Add the value of the current node, then check if it has any children. If so, iterate over each child, call the recursive method, and add the resulting final_sum to the current node's final_sum . Each function call has its own value of final_sum , but the function call on the root node will accumulate final_sum across all child nodes.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM