11# the_algorithms/trees/splay_tree.py
22
3+
34class Node :
45 """A single node in the Splay Tree."""
6+
57 def __init__ (self , key , parent = None , left = None , right = None ):
68 self .key = key
79 self .parent = parent
810 self .left = left
911 self .right = right
1012
13+
1114class SplayTree :
1215 """
1316 A self-adjusting Binary Search Tree (BST) that uses the splay operation
1417 to move the most recently accessed node to the root of the tree.
1518 """
19+
1620 def __init__ (self ):
1721 self .root = None
1822
@@ -43,7 +47,7 @@ def _rotate(self, x: Node):
4347 else :
4448 g .right = x
4549 else :
46- self .root = x # x is the new root
50+ self .root = x # x is the new root
4751
4852 def _splay (self , x : Node ):
4953 """Moves node x to the root of the tree using zig, zig-zig, or zig-zag operations."""
@@ -70,7 +74,7 @@ def search(self, key):
7074 Returns the node if found, otherwise None.
7175 """
7276 curr = self .root
73- last = None # Keeps track of the last node accessed
77+ last = None # Keeps track of the last node accessed
7478
7579 while curr :
7680 last = curr
@@ -83,7 +87,7 @@ def search(self, key):
8387 curr = curr .right
8488
8589 if last :
86- self ._splay (last ) # Splay the last accessed node if key was not found
90+ self ._splay (last ) # Splay the last accessed node if key was not found
8791 return None
8892
8993 def insert (self , key ):
@@ -101,7 +105,7 @@ def insert(self, key):
101105 curr = curr .left
102106 elif key > curr .key :
103107 curr = curr .right
104- else : # Key already exists, splay it and return (or update value)
108+ else : # Key already exists, splay it and return (or update value)
105109 self ._splay (curr )
106110 return
107111
@@ -111,4 +115,4 @@ def insert(self, key):
111115 else :
112116 parent .right = new_node
113117
114- self ._splay (new_node )
118+ self ._splay (new_node )
0 commit comments