我想創建一個對象,我們稱其為模型,其中包含一個屬性,即二叉樹的根。我希望該模型對象具有構建特定深度的二叉樹的方法。我創建了這樣一個類,model它使用了一個樹節點類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和model classes達到我的預期結果?
1 回答

桃花長相依
TA貢獻1860條經驗 獲得超8個贊
為什么不返回構建的節點并獲取引用,如下所示:
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背面放在您的實現中。
添加回答
舉報
0/150
提交
取消