#include <stdio.h>
#include
<stdlib.h>
struct
Node
{
int data;
struct Node* left;
struct Node* right;
};
struct
Node* createNode(int value)
{
struct Node* newNode = (struct
Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = 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 if (value > root->data)
root->right = insert(root->right, value);
return root;
}
struct
Node* queue[100];
int
front = -1, rear = -1;
void
enqueue(struct Node* node)
{
if (rear == 99)
return;
if (front == -1) front = 0;
queue[++rear] = node;
}
struct
Node* dequeue() {
if (front == -1 || front > rear)
return
NULL;
return queue[front++];
}
void
levelOrder(struct Node* root) {
if (!root)
return;
enqueue(root);
while (front <= rear) {
struct Node* current = dequeue();
printf("%d ",
current->data);
if (current->left)
enqueue(current->left);
if (current->right)
enqueue(current->right);
}
}
void
main() {
struct Node* root = NULL;
int n, value;
printf("Enter the number of integers:
");
scanf("%d", &n);
printf("Enter %d integers: ", n);
for (int i = 0; i < n; i++)
{
scanf("%d", &value);
root = insert(root, value);
}
printf("Level-wise traversal: ");
levelOrder(root);
printf("\n");
}
No comments:
Post a Comment