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) { // Found an empty spot: put the new node here if (root == NULL) { return createNode(value); } if (value < root->data) { root->left = insert(root->left, value); // Go left } else { root->right = insert(root->right, value); // Go right } return root; } void printInOrder(struct Node *root) { if (root == NULL) { return; } printInOrder(root->left); // First, everything smaller printf("%d ", root->data); // Then this node printInOrder(root->right); // Then everything bigger } 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]); } printInOrder(root); printf("\n"); freeTree(root); return 0; }
20 30 40 50 60 70 80