struct Node {
int val;
Node* left;
Node* right;
Node(int x) : val(x), left(nullptr), right(nullptr) {}
};
Node* insert(Node* root, int val) {
if (!root) return new Node(val);
if (val < root->val) root->left = insert(root->left, val);
else root->right = insert(root->right, val);
return root;
}
void inorder(Node* root, std::vector<int>& res) {
if (!root) return;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
int main() {
Node* root = nullptr;
int values[] = {10, 5, 15, 3, 7, 12, 18};
for (int v : values) root = insert(root, v);
std::vector<int> result;
inorder(root, result);
for (int x : result) std::cout << x << " ";
return 0;
}Inorder traversal visits nodes in ascending order for a BST. The inserted values create a BST where inorder traversal outputs the sorted list.
The BST property ensures left children are smaller and right children are larger, so at each node you can decide which subtree to search, effectively halving the search space.
Node* insert(Node* root, int val) { if (!root) return new Node(val); if (val < root->val) root->left = insert(root->left, val); else if (val > root->val) root->right = insert(root->right, val); return root; }
The code does not handle the case when val equals root->val, so it returns root without inserting duplicates.
struct Node {
int val;
Node* left;
Node* right;
Node(int x) : val(x), left(nullptr), right(nullptr) {}
};
Node* insert(Node* root, int val) {
if (!root) return new Node(val);
if (val < root->val) root->left = insert(root->left, val);
else root->right = insert(root->right, val);
return root;
}
Node* findMin(Node* root) {
while (root && root->left) root = root->left;
return root;
}
Node* deleteNode(Node* root, int val) {
if (!root) return nullptr;
if (val < root->val) root->left = deleteNode(root->left, val);
else if (val > root->val) root->right = deleteNode(root->right, val);
else {
if (!root->left) {
Node* temp = root->right;
delete root;
return temp;
} else if (!root->right) {
Node* temp = root->left;
delete root;
return temp;
}
Node* temp = findMin(root->right);
root->val = temp->val;
root->right = deleteNode(root->right, temp->val);
}
return root;
}
void inorder(Node* root, std::vector<int>& res) {
if (!root) return;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
int main() {
Node* root = nullptr;
int values[] = {20, 10, 30, 5, 15, 25, 35};
for (int v : values) root = insert(root, v);
root = deleteNode(root, 20);
std::vector<int> result;
inorder(root, result);
for (int x : result) std::cout << x << " ";
return 0;
}Node 20 is replaced by 25 (minimum in right subtree). Then 25 is deleted from its original position. The inorder traversal reflects this change.
Without the BST property, searching may require visiting every node, leading to linear time complexity.
