简体   繁体   English

二叉树所有节点的总和

[英]Sum of all nodes of a Binary Tree

I'm trying to write a program to calculate the sum of all nodes (including the root) in a Binary Tree (not a Binary Search Tree) represented by a list of lists. 我正在尝试编写一个程序来计算由列表列表表示的二叉树(不是二叉搜索树)中所有节点(包括根)的总和。 I conceptually understand that approaching this recursively is the best way to do it but just cannot figure out the code. 我从概念上理解,递归地进行此操作是最好的方法,但无法弄清楚代码。 So far, my code is: 到目前为止,我的代码是:

class BinaryTree:
    def __init__(self,rootObj, leftChild = None, rightChild = None):
        self.key = rootObj
        self.leftChild = None
        self.rightChild = None
        self.node=[rootObj, leftChild, rightChild]
    def getrightChild(self):
        return self.rightChild
    def getleftChild(self):
        return self.leftChild
    def setRootObj(self,obj):
        self.key = obj
    def getRootObj(self):
        return self.key
    def sumTree(BinaryTree):
        if BinaryTree is None: return 0
        return sumTree(BinaryTree.leftChild) \ 
             + sumTree(BinaryTree.rightChild)\
             + BinaryTree.rootObj

print(sumTree([8,[],[]]))
print(sumTree([9, [6, [ ], [ ]], [65, [ ], [ ]]]))

Be careful, 小心,

self.key = rootObj
self.leftChild = None
self.rightChild = None

are object attributes, so you can't access them with through your class directly. 是对象属性,因此您不能直接通过类访问它们。 You have to create an instance like 您必须创建一个实例,例如

obj = BinaryTree(...)

and then call the method 然后调用方法

obj.sumTree(...)

To your sum algorithm, the easiest way to calculate the sum your way would be something like this: 对于求和算法,最简单的计算总和的方法是这样的:

class BinaryTree:       

    @classmethod
    def calc_sum(cls, list_tree):
        print(list_tree)
        if list_tree:
            left_node_value = BinaryTree.calc_sum(list_tree[1])
            right_node_value = BinaryTree.calc_sum(list_tree[2])
            return list_tree[0] + left_node_value + right_node_value
        return 0        

value = BinaryTree.calc_sum([9, [6, [ ], [ ]], [65, [ ], [ ]]])
print(value)

Well, from what I read from this code, your recursive algorithm is correct. 好吧,从我从这段代码中学到的,您的递归算法是正确的。 However, there are many syntax mistakes as well as other, semantic mistakes in it that make it impossible to run correctly. 但是,其中有许多语法错误以及其他语义错误,导致无法正确运行。

Here is what I see: 这是我看到的:

  • You created a BinaryTree class, but you never created an instance of it. 您创建了BinaryTree类,但从未创建它的实例。 sumTree([...]) tries to calculate that sum of a list, which will not work, because you want it to do it for a BinaryTree object. sumTree([...])尝试计算列表的总和,这将不起作用,因为您希望它对BinaryTree对象执行此操作。 You need to parse that list and create an instance of BinaryTree first. 您需要解析该列表并首先创建BinaryTree的实例。 (Like tree = BinaryTree(*write your list here*) maybe. But you need to make your __init__() method allow that passing of the list, of course. See next point.) (例如, tree = BinaryTree(*write your list here*) 。但是,您需要使__init__()方法允许列表的传递。请参阅下一点。)
  • Your __init__() method takes BinaryTree objects as parameters, so there is no parsing of your lists. 您的__init__()方法将BinaryTree对象作为参数,因此不会解析列表。
  • Within the __init__() method, you set both children to None , so no node will ever have child nodes. __init__()方法中,将两个子节点都设置为None ,因此没有节点将拥有子节点。
  • When calling the sumTree() method, you need to specify the context. 调用sumTree()方法时,需要指定上下文。 It needs to be BinaryTree.sumTree(..) . 它必须是BinaryTree.sumTree(..) You still need to create the Binary tree instance that shall be passed to the sumTree method, though. 但是,您仍然需要创建将被传递给sumTree方法的Binary树实例。
  • Within the sumTree() method, you try to access the rootObj member - which does not exist, because you called it key . sumTree()方法中,您尝试访问rootObj成员-该成员不存在,因为您将其称为key

Besides the errors, I'd like to point out some "code smells", if you like. 除了错误之外,如果您愿意,我想指出一些“代码味道”。

  • You should rename the parameter of the sumTree() method to something different ot the class name. 您应该将sumTree()方法的参数重命名为与类名不同的名称。
  • In python, there is no need for Getter-methods. 在python中,不需要Getter方法。 You can access the members directly. 您可以直接访问成员。 If you still wish to define more complex get/set behaviour, you should have a look at python properties . 如果仍然希望定义更复杂的获取/设置行为,则应查看python properties
  • The member node is never used. 成员node从未使用过。

You don't need all the getters . 您不需要所有吸气剂 You can simply use object accessor methods, eg tree_a.left_child . 您可以简单地使用对象访问器方法,例如tree_a.left_child Secondly, you didn't create a BinaryTree out of your children, meaning that it doesn't make sense to run sum_tree on them. 其次,您没有从子级中创建BinaryTree ,这意味着对它们运行sum_tree没有意义。 Read through the following code, and make sure that you understand what's going on. 通读以下代码,并确保您了解发生了什么。

Pretty sure that what you actually want, is this 可以肯定,您真正想要的是这个

class BinaryTree:
    def __init__(self, root, left_child=None, right_child=None):
        self.root = root
        self.left_child = None if not left_child else BinaryTree(*left_child)
        self.right_child = None if not right_child else BinaryTree(*right_child)
        self.node = [root, left_child, right_child]

    def set_root(self, root):
        self.root = root

    def sum_tree(self):
        tree_sum = 0
        if self.left_child:
            tree_sum += self.left_child.sum_tree()
        if self.right_child:
            tree_sum += self.right_child.sum_tree()

        return tree_sum + self.root

tree_a = BinaryTree(8)
tree_b = BinaryTree(9, [6, [], []], [65, [], []])
print(tree_a.sum_tree())
# 8
print(tree_b.sum_tree())
# 80
print(tree_b.left_child.node)
# [6, [], []]

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

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