![](/img/trans.png)
[英]Can't understand this Binary Search Tree (BST) algorithm for Insertion of value in Python
[英]Insertion in Binary Tree (Not BST) Python
我正在尝试在我的二叉树中插入一个节点。 但是,我不知道执行此操作的正确方法。 我知道我应该运行bfs并插入第一个null位置。 如何将其转换为代码?
我尝试使用DFS:树看起来像这样:
class Node:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def insert(node, val):
if not node:
return Node(val)
if not node.left:
node.left = Node(val)
return
if not node.right:
node.right = Node(val)
return
return insert(node.left, val)
return insert(node.right, val)
n1, n2, n3, n4, n5, n6, n7, n8 = Node(1), Node(2), Node(3), Node(4), Node(5), Node(6), Node(7), Node(8)
n1.left, n1.right, n2.left, n2.right, n3.left, n3.right, n4.left = n2, n3, n4, n5, n6, n7, n8
但这给了我无法访问的代码。 正确的方法是什么? 人们对Binary Tree真正的意思是BST感到非常沮丧。
是的,如果您希望平衡它并且不关心值插入的顺序应该广度优先,那么您100%正确,因此我为您修改了一些代码,但我最初所说的仍然有效:
要进行bfs遍历,您必须使用另一个数据结构,即队列。 队列是FIFO,这意味着您最终要在访问下一个级别之前访问每个级别的每个节点。 有趣的是,使此深度首先从末尾弹出,而不是从开头开始模拟堆栈。
def insert(node, val):
"""
Always returns the root of the tree
"""
if not node:
return Node(val)
queue = [node]
while len(queue) > 0:
# n is the current node in the tree
n = queue.pop(0)
# if it has no children insert node
# start from the left
if not n.left:
n.left = Node(val)
return node
if not n.right:
n.right = Node(val)
return node
queue.append(n.left)
queue.append(n.right)
好的! 因此,我希望这是您要寻找的东西,但是您的代码非常好,只需要进行一些更改即可:
class Node:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
def __str__(self): #This allows you to print out the nodes for testing, other "magic" methods can be created here too!
return str(self.val)
def insert(node, val=None):
if not val:
return Node(node) #This will create a new node if val is None
if not node.left:
node.left = val
return
if not node.right:
node.right = val
return
return insert(node.left, val)
return insert(node.right, val)
def main():
n1 = insert(1)
n2 = insert(2)
n3 = insert(3)
n4 = insert(4)
n5 = insert(5)
n6 = insert(6)
n7 = insert(7)
n8 = insert(8)
insert(n1, n2)
insert(n1, n3)
insert(n2, n4)
insert(n2, n5)
insert(n3, n6)
insert(n3, n7)
insert(n4, n8)
print(n1.left)
print(n3.left)
main()
这对我的测试有效! 为了使函数创建新的节点,我更改了insert()
背后的逻辑(尽管我知道这不一定是您想要的方式,您可以将其改回来!)。 尽管有很多其他方法可以实现此功能,但是我认为这是最接近原始代码的方法。
希望能帮助到你!
PS另一个很棒的资源是Interactive Python (授予本章的内容是有关BST的)。 将来仍然有用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.