Skip to content

Commit 96f4e36

Browse files
committed
Add doctests for performance_comparison and fix MyPy error
- Add 14 comprehensive doctests to performance_comparison function - Fix MyPy union-attr error at line 259 by adding proper null check - Total doctests increased from 81 to 95 - All tests verify splay tree behavior and BST property maintenance
1 parent 1f0a6b6 commit 96f4e36

File tree

1 file changed

+37
-4
lines changed

1 file changed

+37
-4
lines changed

data_structures/binary_tree/splay_tree.py

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -253,10 +253,11 @@ def insert(self, key: Any) -> None:
253253
return
254254

255255
node.parent = parent
256-
if parent is not None and key < parent.key:
257-
parent.left = node
258-
else:
259-
parent.right = node
256+
if parent is not None:
257+
if key < parent.key:
258+
parent.left = node
259+
else:
260+
parent.right = node
260261

261262
# Splay the newly inserted node to root
262263
self._splay(node)
@@ -621,7 +622,39 @@ def performance_comparison() -> None:
621622
Demonstrate the performance characteristics of Splay Trees.
622623
623624
This shows how splay trees excel at repeated access to the same elements.
625+
626+
Examples:
627+
>>> tree = SplayTree()
628+
>>> for i in range(1, 11):
629+
... tree.insert(i)
630+
>>> tree.size()
631+
10
632+
>>> tree.get_root_key() # Last inserted element
633+
10
634+
>>> # Demonstrate locality of reference - repeated access
635+
>>> for _ in range(5):
636+
... _ = tree.search(5)
637+
>>> tree.get_root_key() # Element 5 is now at root
638+
5
639+
>>> # Verify tree still maintains BST property
640+
>>> tree.inorder()
641+
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
642+
>>> # Test that min/max operations work and splay to root
643+
>>> min_val = tree.find_min()
644+
>>> min_val
645+
1
646+
>>> tree.get_root_key() # Min is now at root
647+
1
648+
>>> max_val = tree.find_max()
649+
>>> max_val
650+
10
651+
>>> tree.get_root_key() # Max is now at root
652+
10
653+
>>> # Verify height is reasonable (not degenerate)
654+
>>> tree.height() < 10
655+
True
624656
"""
657+
import random
625658
import time
626659

627660
print("=== Splay Tree Performance Demonstration ===\n")

0 commit comments

Comments
 (0)