在构建树时如何通过引用传递?

在构建树时如何通过引用传递?,第1张

概述我想创建一个对象,让我们称其为模型,其中包括属性,二叉树的根.我希望该模型对象具有一种构建特定深度的二叉树的方法.我创建了一个这样的类,模型,它使用树节点类binary_tree_node,如下所示:class binary_tree_node: def __init__(self, data): self.data = data

我想创建一个对象,让我们称其为模型,其中包括属性,二叉树的根.我希望该模型对象具有一种构建特定深度的二叉树的方法.

我创建了一个这样的类,模型,它使用树节点类binary_tree_node,如下所示:

class binary_tree_node:    def __init__(self,data):        self.data = data        self.left_child = None        self.right_child = Noneclass model:    def __init__(self,max_depth = 3):        self.root = None        self.max_depth = max_depth    def build_tree(self):        self.build_tree_recursive_helper(self.root,0)    def build_tree_recursive_helper(self,node,current_depth):        # create the new node        node = binary_tree_node('data')        # check base case        if current_depth >= self.max_depth:            return        # make recursive calls        self.build_tree_recursive_helper(node.left_child,current_depth + 1)        self.build_tree_recursive_helper(node.right_child,current_depth + 1)

我希望能够实例化模型,构建树,然后对树进行自省,就像这样

m = model()m.build_tree()print(m.root.data)>>> 'data'

但是相反,在尝试反省时,我得到以下信息:

m = model()m.build_tree()print(m.root.data)
AttributeError                            Traceback (most recent call last)<ipython-input-138-eaa2b3c07e85> in <module>      1 m = model()      2 m.build_tree()----> 3 print(m.root.data)AttributeError: 'nonetype' object has no attribute 'data'

这违反了我的理解,即python传递对象引用而不是值.

如何修改我的binary_tree_node和模型类以实现预期的结果?

最佳答案为什么不返回构建的节点并获取引用,如下所示:

max_depth = 4def build_tree_recursive_helper(current_depth):     # check base case    if current_depth >= max_depth:        return None     node = binary_tree_node('data')    # make recursive calls    node.left_child = build_tree_recursive_helper(current_depth + 1)    node.right_child = build_tree_recursive_helper(current_depth + 1)    return node

请注意,您必须将自身放回实现中. 总结

以上是内存溢出为你收集整理的在构建树时如何通过引用传递? 全部内容,希望文章能够帮你解决在构建树时如何通过引用传递? 所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1199657.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存