💡 The output list shows the tree nodes in ascending order including the new value.
reconstruct
Final BST with inserted value
The final BST includes the new node with value 5 as left child of 7, maintaining BST properties.
💡 This final state confirms the insertion is complete and correct.
💡 The tree structure and inorder traversal confirm the algorithm's correctness.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insertIntoBST(root, val):
# STEP 1: Check if tree is empty
if root is None:
return TreeNode(val) # STEP 1
curr = root # STEP 2
parent = None # STEP 2
while curr: # STEP 3
parent = curr # STEP 4
if val < curr.val: # STEP 3
if curr.left is None: # STEP 6
curr.left = TreeNode(val) # STEP 7
return root # STEP 8
curr = curr.left # STEP 5
else:
if curr.right is None: # Not reached in this example
curr.right = TreeNode(val)
return root
curr = curr.right # STEP 3
return root
# Driver code
if __name__ == '__main__':
root = TreeNode(4)
root.left = TreeNode(2, TreeNode(1), TreeNode(3))
root.right = TreeNode(7)
val = 5
root = insertIntoBST(root, val)
def inorder(node):
return inorder(node.left) + [node.val] + inorder(node.right) if node else []
print(inorder(root)) # STEP 9
📊
Insert into a BST - Watch the Algorithm Execute, Step by Step
Watching each pointer move and comparison helps you understand how BST insertion preserves order and structure.
Step 1/10
·Active fill★Answer cell
42713
Current node: 1
42713
Current node: 1
42713
Current node: 3
42713
42713
42713
Current node: 6
427135
427135
Return: 1
427135
Result: [1, 2, 3, 4, 5, 7]
427135
Result: [1, 2, 3, 4, 5, 7]
Return: 1
Key Takeaways
✓ Insertion in BST is done by traversing from root to the correct leaf position based on comparisons.
This traversal logic is hard to visualize from code alone but becomes clear when watching pointer moves.
✓ Parent pointer is essential to attach the new node once the correct null child is found.
Understanding the role of parent helps clarify how the tree structure is modified.
✓ Inorder traversal after insertion confirms the BST property is maintained and the new value is correctly placed.
Seeing the sorted output visually confirms correctness beyond just code inspection.
Practice
(1/5)
1. Consider the following code snippet implementing the optimal approach for Two Sum IV in BST. Given the BST with nodes [5,3,6,2,4,null,7] and target k=9, what is the value of variable s during the first iteration of the while loop?
Hint: Inorder array first + last sum equals target [OK]
Common Mistakes:
Off-by-one error in indexing left or right
Confusing node values with indices
Miscomputing sum s
2. Consider the following buggy code snippet for converting a sorted array to a height-balanced BST. Which line contains the subtle bug that can cause infinite recursion or stack overflow?
medium
A. Line 5: left_child = self.helper(nums, left, mid - 1)
B. Line 3: mid = (left + right) // 2
C. Line 7: root.right = self.helper(nums, mid + 1, right)
D. Line 2: if left >= right: return None
Solution
Step 1: Understand base case condition
The base case should be when left > right, not left >= right, to allow single-element subarrays.
Step 2: Consequence of incorrect base case
Using left >= right causes the recursion to skip processing subarrays of size 1, leading to infinite recursion or missing nodes.
Final Answer:
Option D -> Option D
Quick Check:
Base case must allow left == right to process single elements [OK]
Hint: Base case must be left > right, not left >= right [OK]
Common Mistakes:
Incorrect base case causing infinite recursion
Misplaced mid calculation
3. What is the worst-case time complexity of the optimized recursive BST node deletion algorithm that uses the in-order successor to replace a node with two children?
medium
A. O(h) where h is the height of the BST
B. O(h^2) due to recursive calls and successor search
C. O(log n) always, since BST is balanced
D. O(n) where n is the total number of nodes in the BST
Solution
Step 1: Identify height-based operations
Deletion involves searching down the tree (O(h)) and finding the in-order successor, which is also O(h) in worst case.
Step 2: Combine operations and recursion
Successor search and recursive deletion happen along a path of length h, so total time is O(h), not O(h^2).
Final Answer:
Option A -> Option A
Quick Check:
Time proportional to tree height, not total nodes or squared height [OK]
Hint: Deletion time depends on tree height, not total nodes [OK]
Common Mistakes:
Assuming balanced BST always (log n)
Confusing recursion depth with squared complexity
Thinking successor search adds extra factor
4. What is the time and space complexity of the optimal inorder traversal BST validation algorithm for a tree with n nodes and height h?
medium
A. Time O(n), Space O(h) due to recursion stack where h is tree height
B. Time O(n log n), Space O(n) due to storing all nodes
C. Time O(n^2), Space O(1) because no extra data structures are used
D. Time O(n), Space O(n) because all nodes are stored during traversal
Solution
Step 1: Identify time complexity
The algorithm visits each node exactly once in inorder traversal, so time is O(n).
Step 2: Identify space complexity
Space is O(h) due to recursion stack, where h is the height of the tree; no extra arrays store all nodes.
Final Answer:
Option A -> Option A
Quick Check:
Linear time and stack space proportional to tree height [OK]
Hint: Inorder traversal visits each node once, stack depth = tree height [OK]
Common Mistakes:
Confusing recursion stack space with storing all nodes
Assuming O(n log n) due to sorting
Ignoring recursion stack space
5. Suppose the BST can contain duplicate values, and you want to find all nodes with a given value. Which modification to the optimal iterative search algorithm correctly finds all such nodes?
hard
A. Stop at the first found node and return it, since duplicates are not allowed in BSTs.
B. Modify the search to continue searching both left and right subtrees even after finding a matching node.
C. Traverse the entire tree recursively to collect all nodes with the target value, ignoring BST property.
D. Use a queue to perform BFS and collect all nodes with the target value efficiently.
Solution
Step 1: Understand duplicates in BST
Duplicates can appear on either left or right subtree depending on BST definition.
Step 2: Modify search to find all matches
After finding a node with val, continue searching both subtrees to find all duplicates.
Step 3: Avoid full traversal
Using BST property to prune search still possible by checking subtrees where duplicates may exist.
Final Answer:
Option B -> Option B
Quick Check:
Continuing search after first match finds all duplicates [OK]
Hint: Duplicates require searching both subtrees after match [OK]
Common Mistakes:
Stopping at first match or ignoring BST property completely