Balanced BST Implementation

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-05-03

Problem Statement


Design and implement a Balanced Binary Search Tree data structure that supports:


1.Insertion of elements while maintaining balance.
2.Deletion of elements while maintaining balance.
3.Searching for a specific element.
4.In-order, Pre-order, and Post-order traversals.
5.Validation that the tree remains balanced after each operation.


You may implement any self-balancing variant (e.g., AVL Tree or Red-Black Tree).


✅ Functional Requirements

Insert(key)

•Insert a node into the BST.
•Rebalance the tree if necessary.

Delete(key)

•Remove a node from the BST.
•Rebalance the tree if necessary.

Search(key)

•Find whether a given value exists in the tree.

Traversal Methods

•Implement inOrder(), preOrder(), and postOrder() traversals.

Balance Check

•Provide a utility to check if the tree is height-balanced.


⚙️ Non-Functional Requirements


Aspect with Description


Time Complexity

All major operations (insert, delete, search) should be O(log n)


Space Complexity

Should use O(n) space for tree storage


Scalability

Should handle large numbers of insertions efficiently


Extensibility

Should allow adding additional features (e.g., range queries, min/max lookup)


Correctness

Tree must maintain BST ordering and balancing properties after each operation


🧱 Key Classes / Interfaces


•Node — represents each element in the tree
•Fields: key, left, right, height (or color for Red-Black Tree)
•BalancedBST — manages tree operations
•Methods:
•insert(int key)
•delete(int key)
•search(int key)
•inOrder(), preOrder(), postOrder()
•getHeight(Node node)
•getBalanceFactor(Node node)
•rotateLeft(Node node)
•rotateRight(Node node)


💡 Example Scenario -------------------------

1 2Input: Insert keys [10, 20, 30, 40, 50, 25] 3Output: Tree is balanced after each insertion (as per AVL rotation rules) 4 5Inorder Traversal after all insertions: [10, 20, 25, 30, 40, 50] 6Search(25): Found 7Delete(40): Tree rebalanced


💬 Discussion Points (for Interview)

•How do you detect unbalanced nodes?
•What are the rotation types in AVL or Red-Black Trees?
•Difference between AVL and Red-Black trees in performance and use case?
•How to handle duplicate keys?
•How would you extend this to support range queries (like finding all values between x and y)?


🧠 Design Hints


If implementing an AVL Tree:

•Balance Factor = height(left subtree) - height(right subtree)
•Rotate when |Balance Factor| > 1
•Left Rotation
•Right Rotation
•Left-Right Rotation
•Right-Left Rotation


🧾 Final Interview Prompt

Design and implement a Balanced Binary Search Tree (BST) supporting insertion, deletion, search, and traversal operations.
Ensure that the tree automatically rebalances after every insertion or deletion to maintain O(log n) performance.
Discuss how you detect and correct imbalance and which balancing approach (AVL or Red-Black) you used.


Solution

Comments