在尝试使用 Python 实现二叉查找树 (BST) 时,我们遇到了一个问题。当我们试图向树中添加元素时,程序会报错。
2、解决方案
为了解决这个问题,我们仔细检查了 BST 的实现代码,发现了一个问题。在原始代码中,我们在 Node
类中初始化了 self.left
和 self.right
为 None
,而在 BST
类中的 add_word
方法中,我们使用 if
语句检查 current.left
和 current.right
是否为 None
来判断是否要将新节点添加到子树中。但是,当我们一开始创建 BST 时,self.root
是一个空的节点,self.root.left
和 self.root.right
自然也是 None
。因此,当我们尝试向树中添加第一个元素时,条件 if(current.left)
和 if(current.right)
总是会为真,导致程序进入死循环。
为了解决这个问题,我们修改了 BST
类中的 add_word
方法,将 if(current.left)
和 if(current.right)
改为 if(current.left is None)
和 if(current.right is None)
,这样就可以正确判断是否需要将新节点添加到子树中了。
以下是修改后的 BST
类中的 add_word
方法:
def add_word(self,word,meaning):
if(self.root.word is None):
self.root.word=word
self.root.meaning=meaning
return "Create root"
else:
current=self.root
while(1):
if(word<current.word):
if(current.left is None):
current.left=Node(word,meaning)
break
else:
current=current.left
elif(word>current.word):
if(current.right is None):
current.right=Node(word,meaning)
break
else:
current=current.right
else:
break
修改后的代码可以正确地将元素添加到 BST 中,并且不会再出现死循环。
以下是完整的 Python 二叉查找树实现代码:
class Node:
def __init__(self,word,meaning):
self.left=None
self.right=None
self.word=word
self.meaning=meaning
class BST:
def __init__(self,word,meaning):
self.root=Node(word,meaning)
def add_word(self,word,meaning):
if(self.root.word is None):
self.root.word=word
self.root.meaning=meaning
return "Create root"
else:
current=self.root
while(1):
if(word<current.word):
if(current.left is None):
current.left=Node(word,meaning)
break
else:
current=current.left
elif(word>current.word):
if(current.right is None):
current.right=Node(word,meaning)
break
else:
current=current.right
else:
break
def in_order(self,node):
if(node!=None):
self.in_order(node.root.left)
print(node.root.word,node.root.meaning)
self.in_order(node.root.right)
希望这篇技术文章对您有所帮助,如果您有任何其他问题,欢迎随时提问。