在trap中旋转,同时跟踪父节点
我的treap 维护了堆和BST 属性,但是treap 中每个节点的父节点并不总是正确的,我认为这是因为我的旋转方式。
这是我的旋转函数:
def left_rotate(self, child, parent):
L = child.left_child
new_parent = parent.parent
child.left_child = parent
parent.right_child = L
parent.parent = child
child.parent = new_parent
return child
def right_rotate(self, child, parent):
R = child.right_child
new_parent = parent.parent
child.right_child = parent
parent.left_child = R
parent.parent = child
child.parent = new_parent
return child
这是我的trap的一个示例,显示了正确的堆(顶部的最大值)和BST,但没有正确的父级。
格式为[优先级]<键值>位置父母。
[62319] <3 c> root
[14267] <1 e> left _3_
[43408] <12 b> right _3_
[14605] <4 f> left _3_
[7853] <6 a> right _4_
[35669] <17 d> right _12_
正如您所看到的,优先级为 [14605] 的节点有一个不正确的父节点。我的旋转函数有什么问题导致这种行为?
My treap maintains both the heap and BST properties, but the parent nodes of each node in the treap isn't always correct, and I think it's because of how I'm rotating.
Here are my rotation functions:
def left_rotate(self, child, parent):
L = child.left_child
new_parent = parent.parent
child.left_child = parent
parent.right_child = L
parent.parent = child
child.parent = new_parent
return child
def right_rotate(self, child, parent):
R = child.right_child
new_parent = parent.parent
child.right_child = parent
parent.left_child = R
parent.parent = child
child.parent = new_parent
return child
Here is an example of my treap showing correct heap (max at top) and BST, but not correct parents.
Format is [priority] <key value> position parent.
[62319] <3 c> root
[14267] <1 e> left _3_
[43408] <12 b> right _3_
[14605] <4 f> left _3_
[7853] <6 a> right _4_
[35669] <17 d> right _12_
As you can see the node at priority [14605] has an incorrect parent. What is wrong with my rotate functions to cause such behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这两个函数都有相同的错误,所以我现在重点关注左旋转。有两个指针未设置:
new_parent
以前将parent
作为其子级,但最后应该将child
作为其子级,但是您没有更改new_parent
的任何指针L
以前将child
作为其父级,但最后应该有parent< /code> 作为其父级,但您没有更改任何
L
的指针更正后的函数是:
我不确定您是否有其他 Tree 属性,例如
root
节点,但树的根可能会在一个旋转。另外,有一点需要注意的是,旋转函数有一个返回值,这有点奇怪。Both functions have the same mistake, so I'll focus on left-rotate for now. There are two pointers not being set:
new_parent
previously hadparent
as its child, but at the end should havechild
as its child, but you haven't changed any ofnew_parent
's pointersL
previously hadchild
as its parent, but at the end should haveparent
as its parent, but you haven't changed any ofL
's pointersThe corrected functions are then:
I'm not sure if you have other Tree attributes, like a
root
node, but the root of the tree might change during a rotate. Also, on a minor note, it's a tiny bit odd that the rotate function has a return value.