如何在沒有輔助函式的情況下在二叉搜索樹類中實作遞回方法?例如,我下面的代碼具有add使用preorder輔助函式實作的函式,用于傳遞必要的引數。
到目前為止,我嘗試在沒有幫助器的情況下實作其中任何一個都失敗了,因為我得到了以下代碼:
preorder_with_helper:
[8, 4, 2, 6, 12, 10, 14]
預購:
Traceback (most recent call last):
File "/Users/briannakemp/Documents/coding/python/tree_recursion", line 7, in <module>
class BST:
File "/Users/briannakemp/Documents/coding/python/tree_recursion", line 37, in BST
def preorder(self, root=self.root, data=[]) -> [int]:
NameError: name 'self' is not defined
我究竟做錯了什么?我的代碼如下:
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def add_with_helper(self, value):
def helper(root):
if not root: return TreeNode(value)
if value > root.value:
root.right = helper(root.right)
if value < root.value:
root.left = helper(root.left)
return root
self.root = helper(self.root)
def preorder_with_helper(self) -> [int]:
def helper(root, data):
if not root: return data
data.append(root.value)
if root.left: helper(root.left, data)
if root.right: helper(root.right, data)
return data
return helper(self.root, [])
def preorder(self, root=self.root, data=[]) -> [int]:
if not root: return data
data.append(root.value)
if root.left: helper(root.left, data)
if root.right: helper(root.right, data)
return data
t = BST()
t.add_with_helper(8)
t.add_with_helper(4)
t.add_with_helper(12)
t.add_with_helper(6)
t.add_with_helper(2)
t.add_with_helper(10)
t.add_with_helper(14)
print(t.preorder_with_helper())
print(t.preorder())
uj5u.com熱心網友回復:
您不能將 self.root 作為引數傳遞 - 相反,您可以這樣做:print(t.preorder(t.root))
另外,我認為您的代碼正在呼叫一個“助手”函式,它不是 BST 類的屬性-
def preorder(self, root=None, data=[]) -> [int]:
if not root: return data
data.append(root.value)
if root.left: self.preorder(root.left, data)
if root.right: self.preorder(root.right, data)
return data
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/435102.html
