2015-11-21 80 views
-1

我試圖實現一個BST,並正在插入。我想打電話給一些簡單的東西,比如tree.insert(Node(1))。但問題是這個binaryInsert不會持續。什麼是實現這種功能的最佳方式?插入不堅持樹

class Node: 
    def __init__(self, data): 
     self.value = data 
     self.rightChild = None 
     self.leftChild = None 

class Tree: 
    def __init__(self): 
     self.root = None 

    def binaryInsert(self, root, node): 
     if root == None: 
      root = node 
     else: 
      if root.value > node.value: 
       if root.leftChild == None: 
        root.leftChild = node     
       else: 
        self.binaryInsert(root.leftChild, node) 
      else: 
       if root.rightChild == None: 
        root.rightChild = node     
       else: 
        self.binaryInsert(root.rightChild, node) 

    def insert(self, node): 
     self.binaryInsert(self.root, node) 
+0

你會得到什麼錯誤?你能澄清你的問題嗎? –

回答

-1

考慮從以下幾行代碼:

def binaryInsert(self, root, node): 
    if root == None: 
     root = node 

這裏你只是覆蓋本地根變量(作用域爲方法),我已經糾正了你的代碼,隨意問任何問題:

class Node: 
    def __init__(self, data): 
     self.value = data 
     self.rightChild = None 
     self.leftChild = None 

class Tree: 
    def __init__(self): 
     self.root = None 

    def binaryInsert(self, tree, node): 
     if tree.root == None: 
      tree.root = node 
     else: 
      if tree.root.value > node.value: 
       if tree.root.leftChild == None: 
        tree.root.leftChild = node     
       else: 
        self.binaryInsert(tree.root.leftChild, node) 
      else: 
       if tree.root.rightChild == None: 
        tree.root.rightChild = node     
       else: 
        self.binaryInsert(tree.root.rightChild, node) 

    def insert(self, node): 
     self.binaryInsert(self, node)