在学习hackerrank中的BST时,我遇到了以下问题。
我的Node和Binary Search Tree的类定义如下:
class Node:
def __init__(self,info):
self.info = info
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self,val):
currentNode = self.root
if currentNode is None:
self.root = Node(val)
elif currentNode.info > val:
currentNode.left = insert(currentNode.left,val)
elif currentNode.info < val:
currentNode.right = insert(currentNode.right,val)
return currentNode
但是,在for循环上使用tree = BinarySearchTree()
对某些整数数组tree.insert(arr[i]
使用arr
后,在class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None
def __str__(self):
return str(self.info)
def preOrder(root):
if root == None:
return
print (root.info, end=" ")
preOrder(root.left)
preOrder(root.right)
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self,val):
currentNode = self.root
if currentNode is None:
self.root = Node(val)
elif currentNode.info > val:
currentNode.left = insert(currentNode.left,val)
elif currentNode.info < val:
currentNode.right = insert(currentNode.right,val)
return currentNode
tree = BinarySearchTree()
t = int(input())
arr = list(map(int, input().split()))
for i in range(t):
tree.insert(arr[i])
preOrder(tree.root)
上执行遍历将没有输出。该逻辑对我来说似乎是正确的,并且我怀疑这是由于Node和BST之间的类型不同引起的,但是我不确定如何解决此问题。
编辑:以下是hackerrank的完整代码。我唯一能编辑的就是插入功能。
6
4 2 3 1 7 6
给定的测试用例是
4 2 3 1 7 6
并且应该返回Traceback (most recent call last):
File “solution.py”, line 40, in <module>
tree.insert(arr[i])
File “solution.py”, line 30, in insert
currentNode.left = insert(currentNode.left,val)
NameError: name ‘insert’ is not defined
,但未返回任何输出。
编辑:根据第一个答案进行更改!现在,我有以下一周错误:
//get the row sums
mtx.multiply(MatrixUtils.createRealMatrix(new double[][]{{1}, {1}}))
> Array2DRowRealMatrix{{3.0},{7.0},{11.0}}
//get the column sums
MatrixUtils.createRealMatrix(new double[][]{{1, 1, 1}}).multiply(mtx)
> Array2DRowRealMatrix{{9.0,12.0}}
答案 0 :(得分:0)
我认为问题出在这里
def insert(self,val):
currentNode = self.root
if currentNode is None:
currentNode = Node(val)
elif currentNode.info > val:
currentNode.left = insert(currentNode.left,val)
elif currentNode.info < val:
currentNode.right = insert(currentNode.right,val)
return currentNode
如您所见,您确实“插入”了节点,但未分配代码块
if currentNode is None:
currentNode = Node(val)
应该是
if currentNode is None:
self.root = Node(val)
您继续尝试遍历Null树
编辑:这可能不是问题所在,请提供完整的代码create()
函数从您的代码中丢失,但是被称为
答案 1 :(得分:0)
将代码更改为
def insert(self, val, currentNode):
if self.root is None:
self.root = Node(val)
elif currentNode.info > val:
if currentNode.left is None
currentNode.left = Node(val)
else:
self.insert(val, currentNode.left)
elif currentNode.info < val:
if currentNode.right is None
currentNode.right = Node(val)
else:
self.insert(val, currentNode.right)
并通过
调用 tree.insert(val,tree.root)
答案 2 :(得分:0)
这里的版本略短一些,它避免了嵌套的“ if”语句,并且没有“ Node”类:
{{1}}