Data Structures & AlgorithmsMedium
Let's explore binary search trees. Consider that you are given a stream of numerical data. Your task is to design and implement a self-balancing binary search tree (BST) data structure that efficiently supports the following operations: Insertion: Insert a new number into the BST while maintaining its self-balancing property. The balancing mechanism should ensure that the height of the tree remains logarithmic in the number of nodes. Implement the insertion logic and explain the balancing technique used (e.g., AVL trees, Red-Black trees). Search: Given a number, determine if it exists in the BST. Implement an efficient search algorithm that leverages the BST property to locate the number or confirm its absence. Deletion: Remove a number from the BST while maintaining its self-balancing property. Handle different deletion scenarios, such as deleting a leaf node, a node with one child, and a node with two children. Describe how the balancing is preserved after deletion. Range Query: Given a range (min, max), return all numbers within the BST that fall within this range, in sorted order. Optimize the range query to avoid traversing unnecessary parts of the tree. For example, if the stream of numbers is [10, 5, 15, 3, 7, 12, 18], the BST should dynamically adapt to maintain balance as each number is inserted. Demonstrate how your implementation handles operations like inserting 6, deleting 10, and performing a range query for numbers between 6 and 16. Discuss the time complexity of each operation in terms of the number of nodes in the tree (n) and the height of the tree (h). Pay close attention to edge cases and error handling in your implementation.