2017-01-24 3 views
0

Я настроен на поиск двоичного дерева, как один 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 

ответ

2

Да, вы правы, я немного прикрутил его.

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''' if self.root is None: self.root = Node() self.root.data = newvalue else: self.push(self.root, newvalue) def push(self, node, value): # This function puts the value in the correct position in the bintree # Not to be used by user. if value < node.data: if node.left is not None: self.push(node.left,value) else: node.left = Node() node.left.data = value else: if node.right is not None: self.push(node.right,value) else: node.right = Node() node.right.data = value

Я сделал это с нуля рекурсивным. Это проще. Конечно, это не сработало, потому что в первой попытке вы всегда устанавливаете корень на ни одного, а во втором вы все время обновляете корень (мой плохой)

+0

Изменено то, что вы прокомментировали. Помещенный если я попробовать следующее: 'bintree = Bintree()' ' bintree.put (12)' ' bintree.put (13)' я получаю сообщение об ошибке при выполнении 'bintree.put (13)', что узел существует, но node.data не имеет никакого значения в цикле в push. – user3061876

+0

Теперь он работает! Спасибо за помощь! – user3061876

Смежные вопросы