Recursive insertion logic
What you'll learn: How to use the "smaller to the left, larger to the right" rule to find the perfect spot for new data using recursion.
The "Sorting Office" analogy
Imagine you are standing at the front door of a large office building with a package labeled "42." Your job is to deliver it to its specific cubicle. You meet the manager (the Root) at the door. If the manager’s number is 50, they point you to the left hallway because 42 is smaller. If you meet a supervisor in that hallway labeled 30, they point you to the right because 42 is larger.
You keep moving from person to person until you find an empty desk. That empty spot is exactly where "42" belongs to keep the building organized. In a Binary Search Tree (BST), recursion is the act of "moving to the next hallway" until you find that empty space (NULL).
The logic in code
To insert a node, we compare the new value against the current node. We then call the exact same function on either the left or right child. When we finally hit a NULL pointer, we create the new node and hook it back up to the tree.
struct Node* insert(struct Node* root, int value) {
// Base Case: We found the empty desk!
if (root == NULL) {
return createNode(value);
}
// Recursion: Decide which hallway to take
if (value < root->data) {
// Try to insert in the left subtree
root->left = insert(root->left, value);
} else if (value > root->data) {
// Try to insert in the right subtree
root->right = insert(root->right, value);
}
// Return the (unchanged) node pointer to keep the tree linked
return root;
}
Why recursion works here
Each time insert calls itself, the "problem" gets smaller. You aren't searching the whole tree anymore; you are searching one specific branch. The function waits for the next level to finish its job. Once the new node is created at the very bottom, the "waiting" functions finish one by one, handing the updated memory addresses back up the chain until the entire tree is linked correctly.
Key takeaway
BST insertion uses recursion to drill down to a NULL leaf, placing smaller values on the left and larger values on the right.