简体   繁体   English

什么会使此 BST 代码中的插入方法起作用?

[英]What will make insertion method in this BST code work?

the class seems to be working well except the insertion method.除了插入方法外,class 似乎运行良好。 All the print statement methods are working.所有打印语句方法都有效。 I want to insert a node into the tree but once I call, r.insertion(7,3) , it does not work and says there is no "attribute to key".我想在树中插入一个节点,但是一旦我调用r.insertion(7,3) ,它就不起作用并说没有“键的属性”。 How can I fix this binary search tree?如何修复这个二叉搜索树?

class BinarySearchTree:
    def __init__(self,rootObj):
        self.key = rootObj
        self.leftChild = None
        self.rightChild = None

    def insertLeft(self,newNode):
        if self.leftChild == None:
            self.leftChild = BinarySearchTree(newNode)
        else:
            t = BinarySearchTree(newNode)
            t.leftChild = self.leftChild
            self.leftChild = t

    def insertRight(self,newNode):
        if self.rightChild == None:
            self.rightChild = BinarySearchTree(newNode)
        else:
            t = BinarySearchTree(newNode)
            t.rightChild = self.rightChild
            self.rightChild = t
            
    def insertion(self,root, num):
    
        if root == None:
            return Node(num)
        #check if less than
        
        if num < root.key:
            root.left = insertion(self, root.left, num)
            
        elif num >= root.key:
            root.right = insertion(self, root.right, num)
            
        return root


    def getRightChild(self):
        return self.rightChild

    def getLeftChild(self):
        return self.leftChild

    def setRootVal(self,obj):
        self.key = obj

    def getRootVal(self):
        return self.key


r = BinarySearchTree(7)
print(r.getRootVal())
print(r.getLeftChild())
r.insertLeft(4)
print(r.getLeftChild())
print(r.getLeftChild().getRootVal())
r.insertRight(9)
print(r.getRightChild())
print(r.getRightChild().getRootVal())
r.getRightChild().setRootVal('hello')
print(r.getRightChild().getRootVal())
print(r.insertion(7,3))

Thank you.谢谢你。

Accoding to your function definiton, def insertion(self,root, num) takes 2 main parameters:根据您的 function 定义, def insertion(self,root, num)需要 2 个主要参数:

  1. root : which has to be an object of class BinarySearchTree according to your implementation root :根据您的实现,它必须是 class BinarySearchTree的 object
  2. num , which will be an int num ,这将是一个int

When you call r.insertion(7,3) , the num gets an int;当您调用r.insertion(7,3)时, num得到一个 int; however, the root parameter is also getting an int , which is incorrect (and that's the reason behind the error).但是, root参数也得到一个int ,这是不正确的(这就是错误背后的原因)。 If you want insertion in r , you'll have to call it using r.insertion(r, 3) , since r is the rootnode of the BST where you want to insert the value.如果要插入r ,则必须使用r.insertion(r, 3)调用它,因为r是要插入的 BST 的根节点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM