Insert into a BST
Check if tree is empty
The algorithm checks if the root is None. Since the root exists, it proceeds to initialize pointers.
if root is None:
return TreeNode(val)Initialize pointers: curr = root, parent = None
Set current pointer to root node (4) and parent pointer to None before traversal begins.
curr = root
parent = NoneCompare val with curr.val (5 > 4)
Compare the value to insert (5) with current node's value (4). Since 5 > 4, decide to move to the right child.
if val < curr.val:
...
else:
curr = curr.rightUpdate parent to 4 and move curr to right child (7)
Before moving current pointer to right child (7), update parent pointer to current node (4).
parent = curr
curr = curr.rightCompare val with curr.val (5 < 7)
Compare value to insert (5) with current node's value (7). Since 5 < 7, decide to move to the left child.
if val < curr.val:
curr = curr.leftUpdate parent to 7 and move curr to left child (null)
Update parent pointer to current node (7) before moving current pointer to its left child, which is null indicating insertion point.
parent = curr
curr = curr.leftInsert new node as left child of 7
Since current node (7) has no left child, insert new node with value 5 as left child.
if curr.left is None:
curr.left = TreeNode(val)
return rootReturn updated root after insertion
Insertion complete, return the original root node which now includes the new node.
return rootPerform inorder traversal to verify BST
Perform inorder traversal to produce sorted list of node values, verifying BST property after insertion.
def inorder(node):
return inorder(node.left) + [node.val] + inorder(node.right) if node else []
print(inorder(root))Final BST with inserted value
The final BST includes the new node with value 5 as left child of 7, maintaining BST properties.
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 9Key Takeaways
This traversal logic is hard to visualize from code alone but becomes clear when watching pointer moves.
Understanding the role of parent helps clarify how the tree structure is modified.
Seeing the sorted output visually confirms correctness beyond just code inspection.
