2017-01-24 8 views
0

hereのようなバイナリツリー検索を行うように設定されています。ノードを正しく設定するのに問題があります。リンクリストのPythonでノードをウォークスルー

問題: 新しいノードを作成する必要がある場合、ルートノードが上書きされているようです。最初に

Bintree.put(newValue) 

と呼ばれる新しいノードがBintree.rootで作成されます。 2回目は、ルートノードが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

私は、再帰的に最初からそれをやりました。それはより簡単です。 最初の試行では常にルートをnoneに設定し、2番目では常にルートのみを更新する(私の悪い)

+0

あなたがコメントしたものを変更しました。 'bintree = Bintree()' ' bintree.put(12)' ' bintree.put(13)' ''というbintree.put(13)を実行するとき、私はエラーを取得する:私は次のことをしようと置きますノードは存在しますが、node.dataにはpushのループ内に値がありません。 – user3061876

+0

今すぐご利用ください!ご協力ありがとうございました! – user3061876

関連する問題