write code for binary trees traversal in c
- User
write code for binary trees traversal in c
- Assistant
write code for binary trees traversal in c
Sure! Below is a comprehensive C program that defines a binary tree structure and implements the three primary depth-first traversal methods: Inorder, Preorder, and Postorder. Additionally, it includes a Level Order (Breadth-First) traversal for completeness.
#include <stdio.h>
#include <stdlib.h>
// Definition of a binary tree node
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
// Function to create a new binary tree node
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation error!\n");
exit(EXIT_FAILURE);
}
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// Inorder Traversal (Left, Root, Right)
void inorderTraversal(Node* root) {
if (root == NULL)
return;
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
// Preorder Traversal (Root, Left, Right)
void preorderTraversal(Node* root) {
if (root == NULL)
return;
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// Postorder Traversal (Left, Right, Root)
void postorderTraversal(Node* root) {
if (root == NULL)
return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}
// Queue node for Level Order Traversal
typedef struct QueueNode {
Node* treeNode;
struct QueueNode* next;
} QueueNode;
// Queue structure
typedef struct Queue {
QueueNode* front;
QueueNode* rear;
} Queue;
// Function to create a new queue node
QueueNode* createQueueNode(Node* treeNode) {
QueueNode* newQNode = (QueueNode*)malloc(sizeof(QueueNode));
if (!newQNode) {
printf("Memory allocation error!\n");
exit(EXIT_FAILURE);
}
newQNode->treeNode = treeNode;
newQNode->next = NULL;
return newQNode;
}
// Initialize an empty queue
void initQueue(Queue* q) {
q->front = q->rear = NULL;
}
// Check if the queue is empty
int isQueueEmpty(Queue* q) {
return (q->front == NULL);
}
// Enqueue a tree node
void enqueue(Queue* q, Node* treeNode) {
QueueNode* temp = createQueueNode(treeNode);
if (q->rear == NULL) {
q->front = q->rear = temp;
return;
}
q->rear->next = temp;
q->rear = temp;
}
// Dequeue a tree node
Node* dequeue(Queue* q) {
if (isQueueEmpty(q))
return NULL;
QueueNode* temp = q->front;
Node* treeNode = temp->treeNode;
q->front = q->front->next;
if (q->front == NULL)
q->rear = NULL;
free(temp);
return treeNode;
}
// Level Order Traversal (Breadth-First)
void levelOrderTraversal(Node* root) {
if (root == NULL)
return;
Queue q;
initQueue(&q);
enqueue(&q, root);
while (!isQueueEmpty(&q)) {
Node* current = dequeue(&q);
printf("%d ", current->data);
if (current->left != NULL)
enqueue(&q, current->left);
if (current->right != NULL)
enqueue(&q, current->right);
}
}
// Function to free the binary tree memory
void freeTree(Node* root) {
if (root == NULL)
return;
freeTree(root->left);
freeTree(root->right);
free(root);
}
// Example usage
int main() {
/*
1
/ \
2 3
/ \ \
4 5 6
*/
Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->right = createNode(6);
printf("Inorder Traversal: ");
inorderTraversal(root);
printf("\n");
printf("Preorder Traversal: ");
preorderTraversal(root);
printf("\n");
printf("Postorder Traversal: ");
postorderTraversal(root);
printf("\n");
printf("Level Order Traversal: ");
levelOrderTraversal(root);
printf("\n");
// Free allocated memory
freeTree(root);
return 0;
}
Node Structure:
data and pointers to its left and right children.Creating Nodes:
createNode function allocates memory for a new node, initializes it with the given data, and sets its children to NULL.Depth-First Traversals:
Inorder (Left, Root, Right):
void inorderTraversal(Node* root);
Visits the left subtree, the root node, and then the right subtree.
Preorder (Root, Left, Right):
void preorderTraversal(Node* root);
Visits the root node first, then the left subtree, followed by the right subtree.
Postorder (Left, Right, Root):
void postorderTraversal(Node* root);
Visits the left subtree, the right subtree, and then the root node.
Level Order Traversal:
Queue structure uses linked list nodes (QueueNode) to store tree nodes during traversal.levelOrderTraversal function visits nodes level by level from left to right.Memory Management:
freeTree function recursively frees all nodes in the tree.Example Usage:
main function demonstrates how to create a simple binary tree and perform all four types of traversals, printing the order of node visits.When you run the program, you should see the following output:
Inorder Traversal: 4 2 5 1 3 6
Preorder Traversal: 1 2 4 5 3 6
Postorder Traversal: 4 5 2 6 3 1
Level Order Traversal: 1 2 3 4 5 6
To compile the program, save it in a file named, for example, binary_tree_traversal.c, and use the following command:
gcc -o binary_tree_traversal binary_tree_traversal.c
Then run the executable:
./binary_tree_traversal
Error Handling: The createNode and createQueueNode functions include basic error handling to exit the program if memory allocation fails.
Queue Implementation: For the level order traversal, a linked list-based queue is implemented. Alternatively, you can use an array-based queue for better performance or use existing data structures/libraries if available.
Recursive vs. Iterative: The depth-first traversals are implemented recursively for simplicity. For large trees, consider implementing them iteratively to avoid stack overflow.
Feel free to modify the tree structure in the main function to test different scenarios!
Not yet included in a published release.