Solving Leetcode Interviews in Seconds with AI: Insert into a Binary Search Tree
Introduction
In this blog post, we will explore how to solve the LeetCode problem "701" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them. Example 1: Input: root = [4,2,7,1,3], val = 5 Output: [4,2,7,1,3,5] Explanation: Another accepted tree is: Example 2: Input: root = [40,20,60,10,30,50,70], val = 25 Output: [40,20,60,10,30,50,70,null,null,25] Example 3: Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 Output: [4,2,7,1,3,5] Constraints: The number of nodes in the tree will be in the range [0, 104]. -108 <= Node.val <= 108 All the values Node.val are unique. -108 <= val <= 108 It's guaranteed that val does not exist in the original BST.
Explanation
- Iterative Insertion: Traverse the BST iteratively, comparing the value to insert with the current node's value.
- Find Insertion Point: When an empty child (left or right) is found based on the comparison, insert the new node there.
- Handle Empty Tree: If the root is initially empty, create a new node and return it as the new root.
- Runtime Complexity: O(H), where H is the height of the tree. In the worst case (skewed tree), H = N, so O(N). In the average case (balanced tree), H = log N, so O(log N). Storage Complexity: O(1) - iterative approach uses constant extra space.
Code
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:
"""
Inserts a value into a Binary Search Tree (BST).
Args:
root: The root node of the BST.
val: The value to insert.
Returns:
The root node of the BST after the insertion.
"""
if not root:
return TreeNode(val)
curr = root
while True:
if val < curr.val:
if curr.left:
curr = curr.left
else:
curr.left = TreeNode(val)
break
else:
if curr.right:
curr = curr.right
else:
curr.right = TreeNode(val)
break
return root