[英]Maximum recursion depth exceeded error in Python while implementing Binary Search Tree
我使用Python學習BST,並嘗試實現insert和find方法。 但是我在insertNode方法中遇到了最大遞歸深度超過錯誤。 我是BST數據結構的新手,因此很難在Python中實現這些方法。 我嘗試研究並使代碼類似於互聯網上的代碼,但是仍然出現錯誤。
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def insert(self,data):
temp = Node(data)
if self.root is None:
self.root = temp
else:
self.insertNode(self.root,data)
def insertNode(self,root,data):
temp = Node(data)
if data < self.root.data:
if self.root.left is None:
self.root.left = temp
else:
self.insertNode(self.root.left,data)
elif data > self.root.data:
if self.root.right is None:
self.root.right = temp
else:
self.insertNode(self.root.right,data)
def findinTree(self,root,data):
if self.root is None:
return False
if data == self.root.data:
return True
if data < self.root.data:
self.findinTree(self.root.left,data)
else:
self.findinTree(self.root.right,data)
return False
bst = BST()
bst.insert(30)
bst.insert(10)
bst.insert(50)
bst.insert(90)
bst.insert(100)
bst.insert(15)
請幫助調試錯誤,以便功能按預期工作。
這些方法可能是問題的根源 ;-)原因:
def insertNode(self, root, data):
if data < root.data: # <- use the root parameter ...
if root.left is None:
root.left = Node(data)
else:
self.insertNode(root.left, data)
else:
if root.right is None:
root.right = Node(data)
else:
self.insertNode(root.right, data)
def findinTree(self, root, data):
if root is None:
return False
if data == root.data:
return True
if data < root.data:
return self.findinTree(root.left, data)
else:
return self.findinTree(root.right, data)
NB 代碼未經測試
更新:建議使用VPfB,並且未創建不必要的節點。
在insertNode
您引用的是self.root
,這是樹的根。 相反,您應該引用root
(函數參數)。
實際上,在創建第一個子級別( bst.insert(50)
)之后,樹根的右分支不再是None
,因此它將繼續調用self.insertNode(self.root.right,data)
def insertNode(self,root,data):
temp = Node(data)
if data < root.data:
if root.left is None:
print("Inserting {} on the left branch of {}".format(data, root.data))
root.left = temp
else:
print("Inserting {} on the left branch of {}".format(data, root.data))
self.insertNode(root.left,data)
elif data > root.data:
if root.right is None:
print("Inserting {} on the right branch of {}".format(data, root.data))
root.right = temp
else:
print("Inserting {} on the right branch of {}".format(data, root.data))
self.insertNode(root.right,data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.