You are given the root node of a Binary Search Tree (BST) and a value to insert into the tree. Insert the value into the BST in such a way that the resulting tree remains a valid BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.
Q: Are duplicates allowed in the BST? A: No, the problem guarantees that the new value does not exist in the original BST.
Q: Can the input tree be empty? A: Yes, the tree can be empty, in which case the new value should become the root node.
Q: Should we consider balancing the BST with this insertion? A: No, the problem does not require keeping the tree balanced, just that it remains a valid BST.
Q: Is the tree guaranteed to be a valid BST before insertion? A: Yes, the tree given will be a valid BST.
To insert a value into a BST:
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insertIntoBST(root: TreeNode, val: int) -> TreeNode:
if root is None:
return TreeNode(val)
current = root
while True:
if val < current.val:
if current.left is None:
current.left = TreeNode(val)
break
else:
current = current.left
else: # val > current.val because duplicates are not allowed
if current.right is None:
current.right = TreeNode(val)
break
else:
current = current.right
return root
The time complexity of this solution is O(H), where H is the height of the BST. In the average case, the height of the BST is O(log N), where N is the number of nodes, but in the worst case (when the tree is skewed), the height can be O(N). Therefore, the time complexity ranges from O(log N) to O(N) depending on the structure of the tree.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?