@@ -19,9 +19,9 @@ class Node:
1919 def __init__ (
2020 self ,
2121 key : int ,
22- parent : Optional [ " Node" ] = None ,
23- left : Optional [ " Node" ] = None ,
24- right : Optional [ " Node" ] = None ,
22+ parent : Node | None = None ,
23+ left : Node | None = None ,
24+ right : Node | None = None ,
2525 ) -> None :
2626 self .key = key
2727 self .parent = parent
@@ -33,7 +33,7 @@ class SplayTree:
3333 """A self-adjusting Binary Search Tree (Splay Tree)."""
3434
3535 def __init__ (self ) -> None :
36- self .root : Optional [ Node ] = None
36+ self .root : Node | None = None
3737
3838 # --- Basic Rotation Operations ---
3939
@@ -80,7 +80,7 @@ def _rotate_right(self, x: Node) -> None:
8080 # --- Core Splay Operation ---
8181
8282 def _splay (self , x : Node ) -> None :
83- """Moves node x to the root of the tree using a sequence of rotations."""
83+ """Moves node x to the root of the tree using rotations."""
8484 while x .parent :
8585 parent = x .parent
8686 grandparent = parent .parent
@@ -93,26 +93,24 @@ def _splay(self, x: Node) -> None:
9393 self ._rotate_right (parent )
9494 else :
9595 self ._rotate_left (parent )
96-
97- # Two rotations are performed: Zig-Zig or Zig-Zag
9896 elif x == parent .left and parent == grandparent .left :
99- # Case 1: Zig-Zig (x, parent, and grandparent all on left)
97+ # Zig-Zig (both left)
10098 self ._rotate_right (grandparent )
10199 self ._rotate_right (parent )
102100 elif x == parent .right and parent == grandparent .right :
103- # Case 1: Zig-Zig (x, parent, and grandparent all on right)
101+ # Zig-Zig (both right)
104102 self ._rotate_left (grandparent )
105103 self ._rotate_left (parent )
106104 elif x == parent .left and parent == grandparent .right :
107- # Case 2: Zig-Zag (x is left child, parent is right child )
105+ # Zig-Zag (left- right)
108106 self ._rotate_right (parent )
109107 self ._rotate_left (grandparent )
110- elif x == parent . right and parent == grandparent . left :
111- # Case 2: Zig-Zag (x is right child, parent is left child )
108+ else :
109+ # Zig-Zag (right- left)
112110 self ._rotate_left (parent )
113111 self ._rotate_right (grandparent )
114112
115- # --- Search Method (Uses splay) ---
113+ # --- Search Method ---
116114
117115 def search (self , key : int ) -> bool :
118116 """Search for a key. If found, splay it to the root."""
@@ -122,18 +120,14 @@ def search(self, key: int) -> bool:
122120 if key == current .key :
123121 found_node = current
124122 break
125- if key < current .key :
126- current = current .left
127- else :
128- current = current .right
123+ current = current .left if key < current .key else current .right
129124
130125 if found_node :
131126 self ._splay (found_node )
132127 return True
133128 return False
134129
135130
136- # --- Example Usage ---
137131if __name__ == "__main__" :
138132 """
139133 Example run:
0 commit comments