Run ❯
Get your
own
website
❯
Run Code
Ctrl+Alt+R
Change Orientation
Ctrl+Alt+O
Change Theme
Ctrl+Alt+D
Go to Spaces
Ctrl+Alt+P
#include
#include
struct Node { int data; struct Node *left; struct Node *right; }; struct Node *createNode(int value) { struct Node *newNode = malloc(sizeof(struct Node)); if (newNode == NULL) { printf("Memory allocation failed\n"); exit(1); } newNode->data = value; newNode->left = NULL; newNode->right = NULL; return newNode; } struct Node *insert(struct Node *root, int value) { if (root == NULL) { return createNode(value); } if (value < root->data) { root->left = insert(root->left, value); } else { root->right = insert(root->right, value); } return root; } // Returns 1 (true) if the value is in the tree int search(struct Node *root, int value) { struct Node *current = root; while (current != NULL) { printf("Checking %d\n", current->data); if (value == current->data) { return 1; // Found it } if (value < current->data) { current = current->left; // Go left } else { current = current->right; // Go right } } return 0; // Not found } void freeTree(struct Node *root) { if (root == NULL) { return; } freeTree(root->left); freeTree(root->right); free(root); } int main() { struct Node *root = NULL; int values[] = {50, 70, 30, 80, 20, 60, 40}; int length = sizeof(values) / sizeof(values[0]); for (int i = 0; i < length; i++) { root = insert(root, values[i]); } if (search(root, 60)) { printf("60 was found!\n"); } else { printf("60 was not found.\n"); } freeTree(root); return 0; }
Checking 50
Checking 70
Checking 60
60 was found!