繁体   English   中英

对 Python 中的 n 叉树的所有节点求和

[英]Sum all nodes of a n-ary tree in Python

我在此链接的 excel 文件中有一个表格:

在此处输入图像描述

如果Input值为1 s,我如何将其读取为 n 叉树并总结 Python 中的所有节点? 如果它的nodesleaves名称也显示在树上会更好。

         15
     /        \
    8          7
  /  \      /     \
  6   2    2       5
/ | \ |   /  \   / | \
3 3 0 2   2  0  0  2  3 

非常感谢您提前提供的帮助。

我的试用码:

class Node:
    def __init__(self, name, weight, children):
        self.children = children
        self.weight = weight
        self.weight_plus_children = weight

    def get_all_weight(self):
        if self.children is None:
            return self.weight_plus_children
        else:
            for child in self.children:
                # print(child)
                print("Child node score", child.get_weigth_with_children())
                self.weight_plus_children += child.get_weigth_with_children()

        return self.weight_plus_children

    def get_weigth_with_children(self):
        return self.weight_plus_children

leaf1 = Node('Evaluation item 1', 3, None)
leaf2 = Node('Evaluation item 2', 3, None)

leaf3 = Node('Evaluation item 3', 3, None)
leaf4 = Node('Evaluation item 4', 1, None)
leaf5 = Node('Evaluation item 5', 1, None)
leaf6 = Node('Evaluation item 6', 2, None)

leaf7 = Node('Evaluation item 7', 2, None)
leaf8 = Node('Evaluation item 8', 2, None)


subroot1 = Node('Ordinary account authentication', 0, [leaf1, leaf2])
subroot2 = Node('Public account identity verification', 0, [leaf3, leaf4, leaf5, leaf6])
subroot3 = Node('Platform equipment information record', 0, [leaf7, leaf8])

root1 = Node('User Management', 0, [subroot1, subroot2])
root2 = Node('Business platform deployment', 0, [subroot3])

root = Node('Business application security', 0, [root1, root2])

print(subroot1.get_all_weight())
print(subroot2.get_all_weight())
print(subroot3.get_all_weight())

print(root1.get_all_weight())
print(root2.get_all_weight())

print(root.get_all_weight())

出去:

Child node score 3
Child node score 3
6
Child node score 3
Child node score 1
Child node score 1
Child node score 2
7
Child node score 2
Child node score 2
4
Child node score 6
Child node score 7
13
Child node score 4
4
Child node score 13
Child node score 4
17

您可以将 integer 分配给树的每个节点,该节点将递归地包含所有子值的总和。

每个节点的初始值为 0。

然后你可以运行这样的递归算法:

def sum_children(root):
    if root is None:
        return 0
    sum_total = 0
    for child in root.get_children():
        child_value = sum_children(child)
        if child_value > 0:
            sum_total += child_value
    root.value = sum_total
    return sum_total

# Call this function on the tree root
sum_children(tree_root)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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