HERE IS THE CODE
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct node {
struct node *leftChild;
int data;
struct node *rightChild;
};
void insert(int, struct node **);
bool searchRecursion(struct node *, int);
bool searchIteration(struct node *, int);
void main() {
int numberOfNodes, i, currentNode, find;
struct node *root = NULL;
printf("Enter number of node\n");
scanf("%d", &numberOfNodes);
printf("Enter the node\n");
for (i=0;i<numberOfNodes;i++) {
scanf("%d", ¤tNode);
insert(currentNode, &root);
}
printf("Enter the number to search\n");
scanf("%d" ,&find);
if(searchRecursion(root, 10)) {
printf("\nfound in recursive searching");
}
if (searchIteration(root, 10)) {
printf("\nfound in iterative searching");
}
}
void insert(int currentNode, struct node **root) {
if (*root == NULL) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp -> data = currentNode;
temp -> leftChild = NULL;
temp -> rightChild = NULL;
*root = temp;
} else if (currentNode < (*root) -> data) {
insert(currentNode, &((*root)->leftChild));
} else {
insert(currentNode, &((*root)->rightChild));
}
}
bool searchRecursion(struct node *root, int targetNode) {
if (root == NULL) {
return false;
} else if (targetNode == root -> data) {
return true;
} else if (targetNode < root -> data) {
searchRecursion(root -> leftChild, targetNode);
} else {
searchRecursion(root -> rightChild, targetNode);
}
}
bool searchIteration(struct node *root, int targetNode) {
while(root != NULL) {
if (root-> data == targetNode) {
return true;
} else if (targetNode < root->data) {
root = root -> leftChild;
} else {
root = root -> rightChild;
}
}
return false;
}
No comments:
Post a Comment