左倾堆

左倾堆(Leftist Heap)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class LeftistNode(object):
def __init__(self, val):
self.val = val
self.dist = 0
self.right = None
self.left = None
self.prnt = None


class LeftistHeap(object):

def inorder(self, root):
if root:
myHeap.inorder(root.left)
print(root.val)
myHeap.inorder(root.right)

def distance(self, root):
if (root is None):
return -1
else:
return root.dist

def merge(self, rootA, rootB):
if (rootA is None):
return rootB
if (rootB is None):
return rootA
if (rootB.val > rootA.val):
temp = rootB
rootB = rootA
rootA = temp
rootA.right = myHeap.merge(rootA.right, rootB)
if (myHeap.distance(rootA.right) > myHeap.distance(rootA.left)):
temp = rootA.right
rootA.right = rootA.left
rootA.left = temp
if (rootA.right is None):
rootA.dist = 0
else:
rootA.dist = 1 + (rootA.right.dist)
return (rootA)

def deletion(self, root):
print("deleted element is ", root.val)
root = myHeap.merge(root.right, root.left)
return root

def insert(self, root):
newnode = LeftistNode(int(input("enter value\n")))
root = myHeap.merge(root, newnode)
print("root element is ", root.val, " inorder traversal of tree is:")
myHeap.inorder(root)
return (root)


root = LeftistNode(1)
myHeap = LeftistHeap()

参考资料

LeftistHeap-In-Python


左倾堆
https://wangqian0306.github.io/2021/liftist-heap/
作者
WangQian
发布于
2021年11月30日
许可协议