templates/binary-search-tree.cpp
compilable
$cat templates/binary-search-tree
Binary Search Tree
Basic BST with insert, delete, search, min/max, and all four traversal orders.
#bst#binary-search-tree#traversal
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <bits/stdc++.h>
using namespace std;
struct Node {
int val;
Node *L, *R;
Node(int v) : val(v), L(nullptr), R(nullptr) {}
};
Node* insert(Node* root, int v) {
if (!root) return new Node(v);
if (v < root->val) root->L = insert(root->L, v);
else root->R = insert(root->R, v);
return root;
}
bool search(Node* root, int v) {
if (!root) return false;
if (root->val == v) return true;
return v < root->val ? search(root->L, v) : search(root->R, v);
}
Node* minNode(Node* root) {
while (root && root->L) root = root->L;
return root;
}
Node* maxNode(Node* root) {
while (root && root->R) root = root->R;
return root;
}
Node* erase(Node* root, int v) {
if (!root) return root;
if (v < root->val) root->L = erase(root->L, v);
else if (v > root->val) root->R = erase(root->R, v);
else {
if (!root->L) { Node* t = root->R; delete root; return t; }
if (!root->R) { Node* t = root->L; delete root; return t; }
Node* succ = minNode(root->R);
root->val = succ->val;
root->R = erase(root->R, succ->val);
}
return root;
}
void inorder(Node* root) {
if (!root) return;
inorder(root->L);
cout << root->val << " ";
inorder(root->R);
}
void preorder(Node* root) {
if (!root) return;
cout << root->val << " ";
preorder(root->L);
preorder(root->R);
}59 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Binary Search Tree
For every node, all values in the left subtree are strictly less and all in the right subtree are strictly greater.
Operations
insert(val) — insert valueerase(val) — delete node (handles leaf, one child, two children cases)search(val) — check if value existsminVal() / maxVal() — find min/maxinorder() / preorder() / postorder() / levelOrder() — traversalsDeletion Cases
When to Use
set/map or balanced BSTs (splay, treap)