我正在尝试在python中编写二叉树实现,但在使用递归添加子节点时遇到错误。我很少使用python,无法理解addChild()在哪里给出了4个args。根据我的理解,我只给出了与函数原型相同的3个。请忽略其他功能实现。
这是我的代码:
Traceback (most recent call last):
File "z.py", line 50, in <module>
obj.addChild(12, "hari")
File "z.py", line 42, in addChild
self.addChild(current.get_rightChild(), key, value)
TypeError: addChild() takes exactly 3 arguments (4 given)
class Node:
def __init__(self, key = None, value = None, leftChild = None, rightChild = None, parent = None):
self.key = key
self.value = value
self.leftchild = leftChild
self.rightChild = rightChild
self.parent = parent
def get_key(self):
return self.key
def get_value(self):
return self.value
def get_leftChild(self):
return self.leftChild
def get_rightChild(self):
return self.rightChild
def get_parent(self):
pass
def isLeaf(self):
pass
def isRoot(self):
pass
class BinaryTree:
def __init__(self, key = None, value = None, leftChild = None, rightChild = None, parent = None):
self.root = Node(key, value, leftChild = None, rightChild = None, parent = None)
def addChild(self, key, value):
if self.root is None:
self.root = Node(key, value, leftChild = None, rightChild = None, parent = None)
else:
current = self.root
if current is None:
current = Node(key = None, value = None, leftChild = None, rightChild = None, parent = None)
elif current.get_key() < key:
self.addChild(current.get_rightChild(), key, value)
elif current.get_key() > key:
self.addChild(current.get_leftChild(), key, value)
obj = BinaryTree(10, "ram")
obj.addChild(12, "hari")
答案 0 :(得分:0)
您的addChild
方法需要3个参数(包括self
),但您传递4个参数(包括self
)。
更改:
def addChild(self, key, value):
到:
def addChild(self, rightChild, key, value):
即在密钥之前再添加一个参数。
<强>更新强>
你得到的错误是:
class BinaryTree:
def __init__(self, key = None, value = None, leftChild = None, rightChild = None, parent = None):
self.root = Node(key, value, leftChild = None, rightChild = None, parent = None)
def addChild(self, key, value):
if self.root is None:
self.root = Node(key, value, leftChild = None, rightChild = None, parent = None)
else:
current = self.root
if current is None:
current = Node(key = None, value = None, leftChild = None, rightChild = None, parent = None)
elif current.get_key() < key:
self.addChild(current.get_rightChild(),key,value)#error here 4 params
elif current.get_key() > key:
self.addChild(current.get_leftChild(),key,value)#error here 4 params
更新2
将addChild
方法替换为:
def addChild(self, key, value):
if self.root is None :
self.root = Node(key, value, leftChild = None, rightChild = None, parent = None)
else:
self._addChild(self.root, key, value)
def _addChild(self, node, key, value):
if(value < node.get_key()):
if(node.leftChild != None):
self._addChild(value, node.leftChild)
else:
node.leftChild = Node(key, value, leftChild = None, rightChild = None, parent = node)
else:
if(node.rightChild != None):
self._addChild(value, node.rightChild)
else:
node.rightChild = Node(key, value, leftChild = None, rightChild = None, parent = node)