3
3
4
4
5
5
class Node :
6
+ """
7
+ Treap's node
8
+ Treap is a binary tree by key and heap by priority
9
+ """
6
10
def __init__ (self , key : int ):
7
11
self .key = key
8
12
self .prior = random ()
@@ -11,28 +15,64 @@ def __init__(self, key: int):
11
15
12
16
13
17
def split (root : Node , key : int ) -> Tuple [Node , Node ]:
14
- if root is None :
18
+ """
19
+ We split current tree into 2 trees with key:
20
+
21
+ Left tree contains all keys less than split key.
22
+ Right tree contains all keys greater or equal, than split key
23
+ """
24
+ if root is None : # None tree is split into 2 Nones
15
25
return (None , None )
16
26
if root .key >= key :
27
+ """
28
+ Right tree's root will be current node.
29
+ Now we split(with the same key) current node's left son
30
+ Left tree: left part of that split
31
+ Right tree's left son: right part of that split
32
+ """
17
33
l , root .l = split (root .l , key )
18
34
return (l , root )
19
35
else :
36
+ """
37
+ Just symmetric to previous case
38
+ """
20
39
root .r , r = split (root .r , key )
21
40
return (root , r )
22
41
23
42
24
43
def merge (left : Node , right : Node ) -> Node :
44
+ """
45
+ We merge 2 trees into one.
46
+ Note: all left tree's keys must be less than all right tree's
47
+ """
25
48
if (not left ) or (not right ):
49
+ """
50
+ If one node is None, return the other
51
+ """
26
52
return left or right
27
53
if left .key > right .key :
54
+ """
55
+ Left will be root because it has more priority
56
+ Now we need to merge left's right son and right tree
57
+ """
28
58
left .r = merge (left .r , right )
29
59
return left
30
60
else :
61
+ """
62
+ Symmetric as well
63
+ """
31
64
right .l = merge (left , right .l )
32
65
return right
33
66
34
67
35
68
def insert (root : Node , key : int ) -> Node :
69
+ """
70
+ Insert element
71
+
72
+ Split current tree with a key into l, r,
73
+ Insert new node into the middle
74
+ Merge l, node, r into root
75
+ """
36
76
node = Node (key )
37
77
l , r = split (root , key )
38
78
root = merge (l , node )
@@ -41,12 +81,22 @@ def insert(root: Node, key: int) -> Node:
41
81
42
82
43
83
def erase (root : Node , key : int ) -> Node :
84
+ """
85
+ Erase element
86
+
87
+ Split all nodes with keys less into l,
88
+ Split all nodes with keys greater into r.
89
+ Merge l, r
90
+ """
44
91
l , r = split (root , key )
45
92
_ , r = split (r , key + 1 )
46
93
return merge (l , r )
47
94
48
95
49
96
def node_print (root : Node ):
97
+ """
98
+ Just recursive print of a tree
99
+ """
50
100
if not root :
51
101
return
52
102
node_print (root .l )
@@ -55,6 +105,13 @@ def node_print(root: Node):
55
105
56
106
57
107
def interactTreap ():
108
+ """
109
+ Commands:
110
+ + key to add key into treap
111
+ - key to erase all nodes with key
112
+
113
+ After each command, program prints treap
114
+ """
58
115
root = None
59
116
while True :
60
117
cmd = input ().split ()
0 commit comments