22Splay Tree implementation in Python.
33
44A Splay Tree is a self-adjusting binary search tree where recently accessed
5- elements are moved closer to the root through rotations (splaying).
5+ elements are moved closer to the root using rotations (splaying).
66This improves access times for frequently used elements.
77
8- Author:yeshuawm999
9- Repository: https://github.com/TheAlgorithms/Python
8+ Reference: https://en.wikipedia.org/wiki/Splay_tree
9+ Author: yeshuawm999
1010"""
1111
12+ < << << << HEAD
1213
1314# class node
1415class Node :
@@ -31,62 +32,118 @@ def __init__(self):
3132 # --- Basic Rotation Operations ---
3233
3334 def _rotate_left (self , x ):
35+ == == == =
36+ from __future__ import annotations
37+ from typing import Optional
38+
39+
40+ class Node :
41+ """A node in the Splay Tree."""
42+
43+ def __init__ (
44+ self ,
45+ key : int ,
46+ parent : Optional [Node ] = None ,
47+ left : Optional [Node ] = None ,
48+ right : Optional [Node ] = None ,
49+ ) -> None :
50+ self .key = key
51+ self .parent = parent
52+ self .left = left
53+ self .right = right
54+
55+
56+ class SplayTree :
57+ """A self-adjusting Binary Search Tree (Splay Tree)."""
58+
59+ def __init__ (self ) -> None :
60+ self .root : Optional [Node ] = None
61+
62+ # --- Basic Rotation Operations ---
63+
64+ def _rotate_left (self , x : Node ) -> None :
65+ > >> >> >> 5 d5b0f04 (Fixed lint issues , added type hints , and cleaned Splay Tree implementation )
3466 """Perform a left rotation around node x (moving x down and right)."""
3567 y = x .right
36- # 1. Update x's right child to be y's left child
68+ if not y :
69+ return
3770 x .right = y .left
3871 if y .left :
3972 y .left .parent = x
4073
74+ < << << << HEAD
4175 # 2. Update y's parent to be x's parent
4276 y .parent = x .parent
4377 if not x .parent :
4478 self .root = y # y becomes the new root
79+ == == == =
80+ y .parent = x .parent
81+ if not x .parent :
82+ self .root = y
83+ > >> >> >> 5 d5b0f04 (Fixed lint issues , added type hints , and cleaned Splay Tree implementation )
4584 elif x == x .parent .left :
4685 x .parent .left = y
4786 else :
4887 x .parent .right = y
4988
89+ << << << < HEAD
5090 # 3. Update y's left child to be x
91+ == == == =
92+ >> >> >> > 5 d5b0f04 (Fixed lint issues , added type hints , and cleaned Splay Tree implementation )
5193 y .left = x
5294 x .parent = y
5395
54- def _rotate_right (self , x ) :
96+ def _rotate_right (self , x : Node ) -> None :
5597 """Perform a right rotation around node x (moving x down and left)."""
5698 y = x .left
57- # 1. Update x's left child to be y's right child
99+ if not y :
100+ return
58101 x .left = y .right
59102 if y .right :
60103 y .right .parent = x
61104
105+ < << << << HEAD
62106 # 2. Update y's parent to be x's parent
63107 y .parent = x .parent
64108 if not x .parent :
65109 self .root = y # y becomes the new new root
110+ == == == =
111+ y .parent = x .parent
112+ if not x .parent :
113+ self .root = y
114+ > >> >> >> 5 d5b0f04 (Fixed lint issues , added type hints , and cleaned Splay Tree implementation )
66115 elif x == x .parent .right :
67116 x .parent .right = y
68117 else :
69118 x .parent .left = y
70119
120+ << << << < HEAD
71121 # 3. Update y's right child to be x
122+ == == == =
123+ >> >> >> > 5 d5b0f04 (Fixed lint issues , added type hints , and cleaned Splay Tree implementation )
72124 y .right = x
73125 x .parent = y
74126
75127 # --- Core Splay Operation ---
76128
129+ < << << << HEAD
77130 def _splay (self , x ):
131+ == == == =
132+ def _splay (self , x : Node ) -> None :
133+ >> >> >> > 5 d5b0f04 (Fixed lint issues , added type hints , and cleaned Splay Tree implementation )
78134 """Moves node x to the root of the tree using a sequence of rotations."""
79135 while x .parent :
80136 parent = x .parent
81137 grandparent = parent .parent
82138
83139 if not grandparent :
84140 # Zig Case (x is a child of the root)
85- # One single rotation (Right if x is left child, Left if x is right child)
141+ # One single rotation (Right if left child, Left if right child)
86142 if x == parent .left :
87143 self ._rotate_right (parent )
88144 else :
89145 self ._rotate_left (parent )
146+ < << << << HEAD
90147
91148 else :
92149 # Two rotations are performed: Zig-Zig or Zig-Zag
@@ -115,26 +172,69 @@ def _splay(self, x):
115172
116173 def search (self , key ):
117174 """Searches for a key. If found, splays it to the root."""
175+ == == == =
176+
177+ # Two rotations are performed: Zig-Zig or Zig-Zag
178+ elif x == parent .left and parent == grandparent .left :
179+ # Case 1: Zig-Zig (x, parent, and grandparent all on left)
180+ self ._rotate_right (grandparent )
181+ self ._rotate_right (parent )
182+ elif x == parent .right and parent == grandparent .right :
183+ # Case 1: Zig-Zig (x, parent, and grandparent all on right)
184+ self ._rotate_left (grandparent )
185+ self ._rotate_left (parent )
186+ elif x == parent .left and parent == grandparent .right :
187+ # Case 2: Zig-Zag (x is left child, parent is right child)
188+ self ._rotate_right (parent )
189+ self ._rotate_left (grandparent )
190+ else :
191+ # Case 2: Zig-Zag (x is right child, parent is left child)
192+ self ._rotate_left (parent )
193+ self ._rotate_right (grandparent )
194+
195+ # --- Search Method (Uses splay) ---
196+
197+ def search (self , key : int ) -> bool :
198+ """Search for a key. If found, splay it to the root."""
199+ >> >> >> > 5 d5b0f04 (Fixed lint issues , added type hints , and cleaned Splay Tree implementation )
118200 current = self .root
119201 found_node = None
120202 while current :
121203 if key == current .key :
122204 found_node = current
123205 break
124- elif key < current .key :
206+ if key < current .key :
125207 current = current .left
126208 else :
127209 current = current .right
128210
129211 if found_node :
212+ < << << << HEAD
130213 self ._splay (found_node ) # Node is brought to the root
214+ == == == =
215+ self ._splay (found_node )
216+ >> >> >> > 5 d5b0f04 (Fixed lint issues , added type hints , and cleaned Splay Tree implementation )
131217 return True
132218 return False
133219
134220
221+ < << << << HEAD
222+ == == == =
223+ # --- Example Usage (for TheAlgorithms CI testing) ---
224+ >> >> >> > 5 d5b0f04 (Fixed lint issues , added type hints , and cleaned Splay Tree implementation )
135225if __name__ == "__main__" :
226+ """
227+ Example:
228+ >>> tree = SplayTree()
229+ >>> tree.root = Node(10)
230+ >>> tree.root.left = Node(5, parent=tree.root)
231+ >>> tree.root.right = Node(15, parent=tree.root)
232+ >>> print("Before search:", tree.root.key)
233+ >>> found = tree.search(5)
234+ >>> print("Found:", found)
235+ >>> print("After splay, new root:", tree.root.key)
236+ """
136237 tree = SplayTree ()
137- # Manually create nodes to demonstrate splay
138238 tree .root = Node (10 )
139239 tree .root .left = Node (5 , parent = tree .root )
140240 tree .root .right = Node (15 , parent = tree .root )
0 commit comments