【问题标题】:Sum of all nodes of a Binary Tree二叉树的所有节点的总和
【发布时间】:2018-05-16 12:50:52
【问题描述】:

我正在尝试编写一个程序来计算由列表列表表示的二叉树(不是二叉搜索树)中所有节点(包括根节点)的总和。我从概念上理解,递归处理是最好的方法,但无法弄清楚代码。到目前为止,我的代码是:

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

【问题讨论】:

  • 那么你的调试器是怎么说的?
  • 你应该决定你的类是代表树还是树节点。如果在某个 var 中保留对根节点的引用,则只能使用节点构建树。节点可以保留对子节点的引用,那么为什么要使用列表来存储树呢?您还必须决定您的 sum 方法是否应该在您的 Tree 或 Node 类中,或者应该是您在树的根节点上调用的免费方法。另请参阅@PatrickHolop 建议。
  • 非常感谢大家的帮助和建议。由于您的帮助,我能够制定出解决方案。很高兴知道这个由聪明乐于助人的社区存在!

标签: python python-3.x list sum binary-tree


【解决方案1】:

小心,

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

是对象属性,因此您不能直接通过您的类访问它们。你必须创建一个像

这样的实例
obj = BinaryTree(...)

然后调用方法

obj.sumTree(...)

对于您的求和算法,计算总和的最简单方法是这样的:

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)

【讨论】:

    【解决方案2】:

    你不需要所有的getter。您可以简单地使用对象访问器方法,例如tree_a.left_child。其次,您没有从您的孩子中创建 BinaryTree,这意味着对他们运行 sum_tree 没有意义。通读以下代码,确保您了解发生了什么。

    很确定你实际上想要的是这个

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

    【讨论】:

      【解决方案3】:

      嗯,从我从这段代码中读到的,你的递归算法是正确的。 但是,其中存在许多语法错误以及其他语义错误,导致无法正确运行。

      这是我看到的:

      • 您创建了一个BinaryTree 类,但您从未创建它的实例。 sumTree([...]) 尝试计算列表的总和,但这是行不通的,因为您希望它为 BinaryTree 对象执行此操作。您需要先解析该列表并创建BinaryTree 的实例。 (可能像 tree = BinaryTree(*write your list here*) 一样。但您当然需要让您的 __init__() 方法允许传递列表。请参阅下一点。)
      • 您的 __init__() 方法将 BinaryTree 对象作为参数,因此不会解析您的列表。
      • __init__() 方法中,您将两个子节点都设置为 None,因此 no 节点将永远有子节点。
      • 调用sumTree()方法时,需要指定上下文。 它必须是BinaryTree.sumTree(..)。不过,您仍然需要创建应传递给 sumTree 方法的二叉树实例。
      • sumTree() 方法中,您尝试访问不存在的rootObj 成员,因为您将其称为key

      除了错误,我想指出一些“代码味道”,如果你愿意的话。

      • 您应该将sumTree() 方法的参数重命名为与类名不同的名称。
      • 在 python 中,不需要 Getter 方法。您可以直接访问成员。如果您仍然希望定义更复杂的 get/set 行为,您应该看看 python properties
      • 成员node 从未使用过。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-02
        相关资源
        最近更新 更多