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
Input Operations["insert", 5]["insert", 3]["search", 3]["insert", 7]Process each operationand splay accessed nodesSplay Algorithm1Zig: Single rotation2Zig-Zig: Double same side3Zig-Zag: Double opposite357Node 3 splayed to rootFinal Result[3, 5, 7]Inorder traversalof final splay tree357Frequently accessed at rootKey Insight:Splay trees automatically optimize for access patterns by moving frequentlyused nodes to the root using intelligent rotation sequences.TutorialsPoint - Splay Tree | Optimal Self-Adjusting BST
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
12.5K Views
Medium Frequency
~45 min Avg. Time
324 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen