Splay Tree - Problem
Implement a Splay Tree data structure with the three essential rotation operations: zig, zig-zig, and zig-zag. A splay tree is a self-adjusting binary search tree where frequently accessed elements are moved closer to the root through splaying operations, optimizing future access times.
Your implementation should support search, insert, and delete operations. When any node is accessed, it should be splayed to the root using the appropriate rotation sequence based on its position relative to its parent and grandparent.
The splaying operations are:
- Zig: Single rotation when the node is a direct child of root
- Zig-Zig: Double rotation when node and parent are both left children or both right children
- Zig-Zag: Double rotation when node and parent are on opposite sides (left-right or right-left)
Return the inorder traversal of the tree after performing all operations.
Input & Output
Example 1 — Basic Insert Operations
$
Input:
operations = [["insert",5],["insert",3],["insert",7],["insert",1]]
›
Output:
[1,3,5,7]
💡 Note:
Insert nodes 5, 3, 7, 1 into splay tree. After each insert, the newly inserted node is splayed to root. Final inorder traversal gives sorted sequence.
Example 2 — Insert and Search
$
Input:
operations = [["insert",10],["insert",5],["search",5],["insert",15]]
›
Output:
[5,10,15]
💡 Note:
Insert 10, then 5. Search for 5 splays it to root. Insert 15. Final tree has 5 at root with 10 and 15 as children.
Example 3 — Multiple Searches
$
Input:
operations = [["insert",20],["insert",10],["insert",30],["search",10],["search",30]]
›
Output:
[10,20,30]
💡 Note:
Build tree with 20, 10, 30. Search 10 brings it to root. Search 30 brings it to root. Final configuration shows frequent access pattern.
Constraints
- 1 ≤ operations.length ≤ 100
- operations[i] is either ["insert", value] or ["search", value]
- -1000 ≤ value ≤ 1000
- All insert values are unique
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code