6.5Binary Search Tree with Linked Nodes
Insert: a new leaf
Insertion walks the same path as search. The difference is at the end: when search reaches NULL it says "not found", while insertion puts the new node right in that empty spot. The new node is always a leaf, and the rest of the tree stays where it is.
- How to find the place for a new value by following the search path
- How the recursive call links the new node to its parent
- What happens when you try to insert a value that is already there
1Idea
Starting at the root, the new value is compared with each node. If it is smaller you go left, if it is larger you go right. When you reach a NULL child, you have found the only place where the value can go without breaking the BST rule. A new node is created there.
The key lines of the code are the assignments: root->left = insert(root->left, value). Every call returns the root of its subtree. If the subtree was empty, that is the new node, and the parent's left or right field is linked to it. If not, the same root comes back and the assignment changes nothing.
For the same reason the function always returns the root of the tree and is called like this: root = insert(root, 65);. On the first insertion into an empty tree, the new node becomes the root itself. In C this means there is no need for a struct TreeNode** parameter.
In these lessons a value appears in the tree only once: if it is already there, no branch is taken and the tree does not change. If repeated values are needed, either each node gets a counter or equal values always go to the same side (for example to the right).
2Step by step
The drawing inserts 65 into a tree holding 50, 30, 70, 20, 40, 60 and 80. The orange node is the one being compared, and the stack on the right shows the open calls.
- Start. We will insert 65. The path a search would follow decides where it goes.
- 65 is larger than 50: a new call opens on the right subtree.
- 65 is smaller than 70: go down into the left subtree of 70.
- 65 is larger than 60: look to the right of 60. It is empty.
- The call on the empty subtree creates a new node and returns its address. The node is not linked to the tree yet.
- The call for 60 writes the returned address into its
rightfield. 65 is now the right child of 60, a new leaf. - On the way back the calls for 70 and 50 rewrite their children with the same addresses; nothing changes.
- Result: the tree has 8 nodes. No other link changed, and the root is still 50.
struct TreeNode { int data; struct TreeNode* left; struct TreeNode* right;}; struct TreeNode* newNode(int value) { struct TreeNode* n = malloc(sizeof(struct TreeNode)); n->data = value; n->left = NULL; n->right = NULL; return n;} struct TreeNode* insert(struct TreeNode* root, int value) { if (root == NULL) return newNode(value); // empty spot: a new leaf if (value < root->data) root->left = insert(root->left, value); // smaller: go left else if (value > root->data) root->right = insert(root->right, value); // larger: go right return root; // equal: not inserted}class TreeNode { int data; TreeNode left, right; TreeNode(int data) { this.data = data; }} TreeNode insert(TreeNode root, int value) { if (root == null) return new TreeNode(value); // empty spot: a new leaf if (value < root.data) root.left = insert(root.left, value); // smaller: go left else if (value > root.data) root.right = insert(root.right, value); // larger: go right return root; // equal: not inserted}class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def insert(root, value): if root is None: return TreeNode(value) # empty spot: a new leaf if value < root.data: root.left = insert(root.left, value) # smaller: go left elif value > root.data: root.right = insert(root.right, value) # larger: go right return root # equal: not insertedThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
The place for the new leaf is found by walking from the root down to a leaf: at most h steps. O(log n) in a balanced tree, O(n) in a tree that has become a chain.
Recursion keeps one call open per level: O(h). A loop version that keeps the parent in a pointer works in O(1) space.
The order of insertion decides the shape of the tree. If the same values are inserted in sorted order, the tree becomes a single branch; the unbalanced trees lesson covers this case.
4Common mistake
The most common mistake is not storing the returned value:
if (value < root->data) insert(root->left, value); // the new node is lostWhen the subtree is empty, the address of the new node comes back but is written nowhere. The node stays in memory and is never linked to the tree. The same mistake happens outside too: with insert(root, 65); the first insertion into an empty tree is lost. It has to be root = insert(root, 65);.
5Try it
If 40, 20, 60, 30 are inserted into an empty BST in that order, where does 30 go?
The answer is B. 30 < 40, so go left to 20. 30 > 20, so look to the right of 20; it is empty, and 30 goes there.
Show the answer
The answer is B. 30 < 40, so go left to 20. 30 > 20, so look to the right of 20; it is empty, and 30 goes there.
In root = insert(root, value), why does the function return the root?
The answer is B. The root only changes when the tree is empty: the first node inserted becomes the root. In a non-empty tree the same root comes back and the assignment changes nothing. This style handles both cases in one line.
Show the answer
The answer is B. The root only changes when the tree is empty: the first node inserted becomes the root. In a non-empty tree the same root comes back and the assignment changes nothing. This style handles both cases in one line.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.