diff --git a/BTree.c b/BTree.c new file mode 100644 index 0000000..27b0e6a --- /dev/null +++ b/BTree.c @@ -0,0 +1,99 @@ +#include +#include + +// Define the structure for a binary tree node +struct Node { + int data; + struct Node* left; + struct Node* right; +}; + +// Function to create a new node +struct Node* createNode(int data) { + struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); + newNode->data = data; + newNode->left = NULL; + newNode->right = NULL; + return newNode; +} + +// Function to insert a node in the binary tree +struct Node* insert(struct Node* root, int data) { + if (root == NULL) { + return createNode(data); + } + if (data < root->data) { + root->left = insert(root->left, data); + } else { + root->right = insert(root->right, data); + } + return root; +} + +// In-order traversal (Left, Root, Right) +void inOrderTraversal(struct Node* root) { + if (root != NULL) { + inOrderTraversal(root->left); + printf("%d ", root->data); + inOrderTraversal(root->right); + } +} + +// Pre-order traversal (Root, Left, Right) +void preOrderTraversal(struct Node* root) { + if (root != NULL) { + printf("%d ", root->data); + preOrderTraversal(root->left); + preOrderTraversal(root->right); + } +} + +// Post-order traversal (Left, Right, Root) +void postOrderTraversal(struct Node* root) { + if (root != NULL) { + postOrderTraversal(root->left); + postOrderTraversal(root->right); + printf("%d ", root->data); + } +} + +// Function to free the memory of the binary tree +void freeTree(struct Node* root) { + if (root != NULL) { + freeTree(root->left); + freeTree(root->right); + free(root); + } +} + +// Main function to demonstrate the binary tree +int main() { + struct Node* root = NULL; + + // Inserting nodes into the binary tree + root = insert(root, 5); + insert(root, 3); + insert(root, 7); + insert(root, 2); + insert(root, 4); + insert(root, 6); + insert(root, 8); + + // Traversals + printf("In-order traversal: "); + inOrderTraversal(root); + printf("\n"); + + printf("Pre-order traversal: "); + preOrderTraversal(root); + printf("\n"); + + printf("Post-order traversal: "); + postOrderTraversal(root); + printf("\n"); + + // Free the allocated memory + freeTree(root); + + return 0; +}