首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在建树时通过引用传递?

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

Stack Overflow用户
提问于 2019-03-29 05:50:08
回答 1查看 166关注 0票数 3

我想创建一个对象,让我们称其为模型,其中包含一个属性,即二叉树的根。我希望这个模型对象有一个方法来构建一个特定深度的二叉树。

我创建了这样一个类model,它使用一个树节点类binary_tree_node,两者如下所示:

class binary_tree_node:
    def __init__(self, data):
        self.data = data
        self.left_child = None
        self.right_child = None

class 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_nodemodel classes才能达到预期效果?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-29 05:58:47

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

max_depth = 4

def 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

注意,您必须将self放回您的实现中。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55407368

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档