
Problem
Solution
Submissions
AVL Tree for Self-Balancing
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Implement an AVL tree data structure that supports the following operations:
Operations
insert(value)
: Insert a value into the AVL tree.delete(value)
: Delete a value from the AVL tree.search(value)
: Search for a value in the AVL tree, return True if found, False otherwise.get_height()
: Return the height of the AVL tree.inorder_traversal()
: Return a list of values in the AVL tree in inorder traversal (left-root-right).
Example 1
- Input: ["AVLTree", "insert", "insert", "insert", "insert", "insert", "inorder_traversal", "get_height", "delete", "inorder_traversal", "get_height"] [[], [10], [20], [30], [40], [50], [], [], [20], [], []]
- Output: [null, null, null, null, null, null, [10, 20, 30, 40, 50], 3, null, [10, 30, 40, 50], 3]
- Explanation:
- Step 1: Initialize an AVL tree.
- Step 2: Insert 10: Tree: 10
- Step 3: Insert 20: Tree: 10 -> 20
- Step 4: Insert 30: Tree rotates: 20 -> (10, 30)
- Step 5: Insert 40: Tree: 20 -> (10, 30 -> 40)
- Step 6: Insert 50: Tree rotates: 30 -> (20 -> 10, 40 -> 50)
- Step 7: inorder_traversal(): [10, 20, 30, 40, 50]
- Step 8: get_height(): 3
- Step 9: delete(20): Tree adjusts: 30 -> (10, 40 -> 50)
- Step 10: inorder_traversal(): [10, 30, 40, 50]
- Step 11: get_height(): 3
Example 2
- Input: ["AVLTree", "insert", "insert", "insert", "search", "search", "delete", "search", "get_height"] [[], [5], [3], [7], [3], [4], [3], [3], []]
- Output: [null, null, null, null, true, false, null, false, 2]
- Explanation:
- Step 1: Initialize an AVL tree.
- Step 2: Insert 5: Tree: 5
- Step 3: Insert 3: Tree: 5 -> 3
- Step 4: Insert 7: Tree: 5 -> (3, 7)
- Step 5: search(3): true (3 is in the tree)
- Step 6: search(4): false (4 is not in the tree)
- Step 7: delete(3): Tree: 5 -> 7
- Step 8: search(3): false (3 has been deleted)
- Step 9: get_height(): 2
Constraints
- -10^9 ≤ value ≤ 10^9
- All values in the tree are unique.
- At most 10^4 calls will be made to insert, delete, search, get_height, and inorder_traversal.
- Time Complexity: O(log n) for insert, delete, and search operations
- Space Complexity: O(n) for storing the tree
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Define a Node class to represent each node in the AVL tree.
- Keep track of the height of each node to maintain balance.
- Implement left and right rotation operations for rebalancing.
- Calculate balance factor as the difference between left and right subtree heights.
- Rebalance the tree when the balance factor exceeds 1 or is less than -1.