#include <stdio.h>
#include <stdlib.h>
// Define a structure for a binary tree node
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to create a new binary tree node
struct Node* createNode(int value) {
struct Node newNode = (struct Node)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Function to insert a new node with a given key
struct Node insert(struct Node root, int key) {
// If the tree is empty, return a new node
if (root == NULL) {
return createNode(key);
}
// Otherwise, recur down the tree
if (key < root->data) {
root->left = insert(root->left, key);
} else if (key > root->data) {
root->right = insert(root->right, key);
}
// return the (unchanged) node pointer
return root;
}
// Function to search a key in the binary tree
struct Node search(struct Node root, int key) {
// Base Cases: root is null or key is present at root
if (root == NULL || root->data == key) {
return root;
}
// Key is greater than root's key
if (key > root->data) {
return search(root->right, key);
}
// Key is smaller than root's key
return search(root->left, key);
}
// Driver program to test above functions
int main() {
struct Node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
int keyToSearch = 60;
struct Node* result = search(root, keyToSearch);
if (result != NULL) {
printf("Key %d found in the binary tree.\n", keyToSearch);
} else {
printf("Key %d not found in the binary tree.\n", keyToSearch);
}
return 0;
}