Trees & BST · Pattern 5 of 12
BST basics: search, insert, delete and build
At every node, the value you want is either here, on the left or on the right, so you walk one path down. Inorder visits the values in sorted order.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- The input is a BST and you search, insert or delete a value
- Build a balanced BST from sorted data
- Something about the sorted order of the values (iterator, swapped nodes, closest values)
- Sum or count values within a range
The template
TreeNode searchBST(TreeNode root, int val) {
while (root != null && root.val != val)
root = val < root.val ? root.left : root.right; // only one side can hold it
return root;
}
TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) return new TreeNode(val); // the empty spot is the place
if (val < root.val) root.left = insertIntoBST(root.left, val);
else root.right = insertIntoBST(root.right, val);
return root;
}
TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (key < root.val) root.left = deleteNode(root.left, key);
else if (key > root.val) root.right = deleteNode(root.right, key);
else {
if (root.left == null) return root.right; // zero or one child
if (root.right == null) return root.left;
TreeNode succ = root.right; // two children: copy the successor
while (succ.left != null) succ = succ.left;
root.val = succ.val;
root.right = deleteNode(root.right, succ.val); // then delete it from the right
}
return root;
} def search_bst(root, val):
while root and root.val != val:
root = root.left if val < root.val else root.right # only one side can hold it
return root
def insert_into_bst(root, val):
if not root:
return TreeNode(val) # the empty spot is the place
if val < root.val:
root.left = insert_into_bst(root.left, val)
else:
root.right = insert_into_bst(root.right, val)
return root
def delete_node(root, key):
if not root:
return None
if key < root.val:
root.left = delete_node(root.left, key)
elif key > root.val:
root.right = delete_node(root.right, key)
else:
if not root.left: # zero or one child
return root.right
if not root.right:
return root.left
succ = root.right # two children: copy the successor
while succ.left:
succ = succ.left
root.val = succ.val
root.right = delete_node(root.right, succ.val) # then delete it from the right
return root TreeNode* searchBST(TreeNode* root, int val) {
while (root && root->val != val)
root = val < root->val ? root->left : root->right; // only one side can hold it
return root;
}
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (!root) return new TreeNode(val); // the empty spot is the place
if (val < root->val) root->left = insertIntoBST(root->left, val);
else root->right = insertIntoBST(root->right, val);
return root;
}
TreeNode* deleteNode(TreeNode* root, int key) {
if (!root) return nullptr;
if (key < root->val) root->left = deleteNode(root->left, key);
else if (key > root->val) root->right = deleteNode(root->right, key);
else {
if (!root->left) return root->right; // zero or one child
if (!root->right) return root->left;
TreeNode* succ = root->right; // two children: copy the successor
while (succ->left) succ = succ->left;
root->val = succ->val;
root->right = deleteNode(root->right, succ->val); // then delete it from the right
}
return root;
} function searchBST(root, val) {
while (root && root.val !== val)
root = val < root.val ? root.left : root.right; // only one side can hold it
return root;
}
function insertIntoBST(root, val) {
if (!root) return new TreeNode(val); // the empty spot is the place
if (val < root.val) root.left = insertIntoBST(root.left, val);
else root.right = insertIntoBST(root.right, val);
return root;
}
function deleteNode(root, key) {
if (!root) return null;
if (key < root.val) root.left = deleteNode(root.left, key);
else if (key > root.val) root.right = deleteNode(root.right, key);
else {
if (!root.left) return root.right; // zero or one child
if (!root.right) return root.left;
let succ = root.right; // two children: copy the successor
while (succ.left) succ = succ.left;
root.val = succ.val;
root.right = deleteNode(root.right, succ.val); // then delete it from the right
}
return root;
} The variations
-
1Walk one path down
Compare with the node and go left or right: search and the minimum (keep going left) never look at the other side. Range sum skips a whole subtree when it is entirely out of range.
Now you solve -
2Insert and delete
Recurse down and re-attach the returned subtree. Insert puts the value at the empty spot it reaches. Delete with two children copies the inorder successor up and deletes it below.
Now you solve -
3Build a balanced BST
The middle of a sorted array is the root, the left half builds the left subtree and the right half the right one. To balance an existing BST, read it into a sorted list with inorder first.
Now you solve -
4Inorder is sorted
Any question about sorted order is an inorder walk. An iterator keeps the iterative inorder stack between calls; swapped nodes show up as places where inorder goes down; the k closest values are a window on the sorted list.
Now you solve -
5More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
Mistakes to avoid
- Delete with two children: replacing the node but forgetting to delete the successor from the right subtree.
- Forgetting
root.left = insert(root.left, val): without the assignment the new node is never attached. - Recover BST: two swapped nodes can be next to each other in inorder. Keep the first bad pair and update only the second node on a later drop.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.