AVL Tree Implementation - Problem

An AVL tree is a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. If at any time they differ by more than one, rebalancing is done to restore this property.

Implement an AVL tree class with the following operations:

  • insert(value) - Insert a value and rebalance if necessary
  • delete(value) - Delete a value and rebalance if necessary
  • search(value) - Search for a value, return true if found
  • getInorder() - Return inorder traversal as an array

For this problem, you need to implement a function that processes a sequence of operations and returns the final inorder traversal of the tree.

Input & Output

Example 1 — Basic AVL Operations
$ Input: operations = [["insert", 10], ["insert", 20], ["insert", 30]]
Output: [10, 20, 30]
💡 Note: Insert 10 (root), 20 (right child), 30 (causes imbalance). AVL performs left rotation: 20 becomes root with 10 left and 30 right. Inorder: [10, 20, 30].
Example 2 — Insert and Delete
$ Input: operations = [["insert", 10], ["insert", 5], ["insert", 15], ["delete", 10]]
Output: [5, 15]
💡 Note: Build tree with 10 as root, 5 left, 15 right. Delete 10: replace with inorder successor 15, leaving 5 as new root and 15 as right child.
Example 3 — Complex Rotations
$ Input: operations = [["insert", 10], ["insert", 5], ["insert", 15], ["insert", 2], ["insert", 7]]
Output: [2, 5, 7, 10, 15]
💡 Note: Multiple insertions creating a balanced AVL tree through automatic rotations. Final inorder traversal gives sorted sequence.

Constraints

  • 1 ≤ operations.length ≤ 100
  • operations[i][0] ∈ {"insert", "delete", "search"}
  • 1 ≤ operations[i][1] ≤ 1000
  • All values in operations are unique for insert/delete

Visualization

Tap to expand
INPUT OPERATIONSALGORITHM STEPSFINAL RESULTinsert(10), insert(20), insert(30)Tree Operations:1. Build initial structure2. Detect imbalance1Insert nodes following BST property2Calculate balance factors3Detect |balance| > 14Perform left rotation201030[10, 20, 30]Key Insight:AVL rotations maintain perfect balance, ensuring all operations stay O(log n) even with sequential insertions.TutorialsPoint - AVL Tree Implementation | Self-Balancing Tree
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
23.4K Views
Medium Frequency
~35 min Avg. Time
892 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