Problem Description
Given the root of a Binary Search Tree (BST) and a value to insert, insert the new value into the tree while maintaining the BST properties. It is guaranteed that the value does not already exist in the tree. Return the root of the modified tree. Multiple valid BST structures may result from the insertion.
Key Insights
- A BST has the property that for any node, all the nodes in its left subtree are smaller and all the nodes in its right subtree are larger.
- Insertion into a BST involves following the BST property and finding the appropriate null location to attach the new node.
- The process can be implemented recursively or iteratively.
- The problem guarantees uniqueness so no duplicate checks are needed.
Space and Time Complexity
Time Complexity: O(h) where h is the height of the BST (in the worst case, for a skewed tree, O(n)). Space Complexity: O(h) for the recursion stack in the recursive approach (or O(1) with an iterative solution).
Solution
We use the BST property to insert the new node. Starting from the root, if the value to insert is less than the current node's value, we proceed to the left subtree; otherwise, we proceed to the right subtree. This continues until we find a null pointer where we can insert the new value as a new node. Key steps:
- Check if the current node is null; if yes, create a new node with the given value.
- Recurse (or iterate) down the tree until the correct insertion point is found.
- Update the left or right pointers accordingly. This approach uses recursion for clarity, though an iterative implementation is also straightforward.