如何将整数数组转换为 BST? - 特别是我如何初始化 BST,然后将节点添加到这个根?
How can I convert an array of integers into a BST? - in particular how can I initialise the BST, then add nodes to this root?
我得到一个 array of integers
,我想转换成 BST
;
class BST:
def __init__(self,value):
self.right = None
self.left = None
self.value = value
def insert(self, value):
if value<self.value:
if not self.left:
self.left = BST(value)
else:
self.left.insert(value)
else:
if not self.right:
self.right = BST(value)
else:
self.right.insert(value)
return self
array = [3,10,5,2,7,6,11]
def insertArrayEntryIntoBst(array):
currentNode = BST()
for i in range(len(array)):
currentNode.insert(array[i])
我遇到的挑战:
我如何initialise the BST
? - 在 insert() function
中,我需要以 if not currentNode: BST(array[0])
行开头吗?
初始化后,我的代码是否适用于 insertArrayEntryIntoBst()
?这个想法只是循环遍历输入数组,让 insert()
函数发挥它的魔力。
在这种情况下我需要 value
参数吗? - 因为数组中的整数值将代表节点及其值? (这将永远是同一件事)
您可以使用数组的第一项在循环外构造第一个节点。
如果需要访问节点。所以也可以退货。
class BST:
def __init__(self,value):
self.right = None
self.left = None
self.value = value
def insert(self, value):
if value<self.value:
if not self.left:
self.left = BST(value)
else:
self.left.insert(value)
else:
if not self.right:
self.right = BST(value)
else:
self.right.insert(value)
return self
def insertArrayEntryIntoBst(array):
currentNode = BST(array[0])
for i in range(1,len(array)):
currentNode.insert(array[i])
return(currentNode)
array = [3,10,5,2,7,6,11]
myNode=insertArrayEntryIntoBst(array)
print(myNode.value);
print(myNode.left.value);
print(myNode.right.value);
我得到一个 array of integers
,我想转换成 BST
;
class BST:
def __init__(self,value):
self.right = None
self.left = None
self.value = value
def insert(self, value):
if value<self.value:
if not self.left:
self.left = BST(value)
else:
self.left.insert(value)
else:
if not self.right:
self.right = BST(value)
else:
self.right.insert(value)
return self
array = [3,10,5,2,7,6,11]
def insertArrayEntryIntoBst(array):
currentNode = BST()
for i in range(len(array)):
currentNode.insert(array[i])
我遇到的挑战:
我如何
initialise the BST
? - 在insert() function
中,我需要以if not currentNode: BST(array[0])
行开头吗?初始化后,我的代码是否适用于
insertArrayEntryIntoBst()
?这个想法只是循环遍历输入数组,让insert()
函数发挥它的魔力。在这种情况下我需要
value
参数吗? - 因为数组中的整数值将代表节点及其值? (这将永远是同一件事)
您可以使用数组的第一项在循环外构造第一个节点。
如果需要访问节点。所以也可以退货。
class BST:
def __init__(self,value):
self.right = None
self.left = None
self.value = value
def insert(self, value):
if value<self.value:
if not self.left:
self.left = BST(value)
else:
self.left.insert(value)
else:
if not self.right:
self.right = BST(value)
else:
self.right.insert(value)
return self
def insertArrayEntryIntoBst(array):
currentNode = BST(array[0])
for i in range(1,len(array)):
currentNode.insert(array[i])
return(currentNode)
array = [3,10,5,2,7,6,11]
myNode=insertArrayEntryIntoBst(array)
print(myNode.value);
print(myNode.left.value);
print(myNode.right.value);