Я настроен на поиск двоичного дерева, как один here. У меня проблема с правильной настройкой узлов.Прогулка по узлам в связанном списке python
Проблема: При создании нового узла корневой узел, по-видимому, перезаписывается. Первый раз
Bintree.put(newValue)
- новый узел создается в Bintree.root. Во второй раз корневой узел, кажется, перезаписывается в functioncall Bintree.put (newValue).
Включает ли эти строки ниже корень узла, когда он выполняется?
node = root
node = node.left # Left is a node below node
node = Node()
Строки, приведенные ниже, являются кодом для моей программы.
# Node for binary tree
class Node():
def __init__(self):
self.data = None
self.left = None
self.right = None
class Bintree:
def __init__(self):
self.root = None
def put(self, newvalue):
'''Sends the new value into the correct position in the Bintree
:param newvalue: The data that's sent to storage'''
self.root = push(self.root, newvalue)
def push(root, value):
# This function puts the value in the correct position in the bintree
# Not to be used by user.
node = root
while node is not None:
if node.data < value:
node = node.left
else:
node = node.right
node = Node()
node.value = value
return node
Изменено то, что вы прокомментировали. Помещенный если я попробовать следующее: 'bintree = Bintree()' ' bintree.put (12)' ' bintree.put (13)' я получаю сообщение об ошибке при выполнении 'bintree.put (13)', что узел существует, но node.data не имеет никакого значения в цикле в push. – user3061876
Теперь он работает! Спасибо за помощь! – user3061876