#include <stdio.h>
#include <stdlib.h>
// Node structure for BST
typedef struct Node {
int val;
struct Node* left;
struct Node* right;
} Node;
// Create new node
Node* newNode(int val) {
Node* node = (Node*)malloc(sizeof(Node));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// Insert value into BST
Node* insert(Node* root, int val) {
if (root == NULL) return newNode(val); // insert at empty spot
if (val < root->val) root->left = insert(root->left, val); // go left
else root->right = insert(root->right, val); // go right
return root;
}
// Search value in BST
int search(Node* root, int val) {
if (root == NULL) return 0; // not found
if (root->val == val) return 1; // found
if (val < root->val) return search(root->left, val); // search left
else return search(root->right, val); // search right
}
// Print BST inorder (sorted)
void inorder(Node* root) {
if (root == NULL) return;
inorder(root->left);
printf("%d ", root->val);
inorder(root->right);
}
int main() {
Node* root = NULL;
int values[] = {10, 5, 15, 3, 7, 20};
int n = sizeof(values)/sizeof(values[0]);
for (int i = 0; i < n; i++) {
root = insert(root, values[i]);
}
printf("BST inorder traversal: ");
inorder(root);
printf("\n");
int target = 7;
if (search(root, target)) {
printf("Found %d in the BST\n", target);
} else {
printf("Did not find %d in the BST\n", target);
}
return 0;
}if (root == NULL) return newNode(val); // insert at empty spot
insert new node when we reach empty position
if (val < root->val) root->left = insert(root->left, val); // go left
go left if value is smaller than current node
else root->right = insert(root->right, val); // go right
go right if value is greater or equal
if (root == NULL) return 0; // not found
stop search if reached empty spot without finding value
if (root->val == val) return 1; // found
found the value, return success
if (val < root->val) return search(root->left, val); // search left
search left subtree if value smaller
else return search(root->right, val); // search right
search right subtree if value greater
BST inorder traversal: 3 5 7 10 15 20
Found 7 in the BST