This C program implements search in Binary search tree. This is the data structure where inorder traversal of the binary search tree leads to sorting of elements.
Here is the source code of the C program to search element in Binary search tree. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to search for an element in a binary search tree
*/
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int data;
struct TreeNode *leftChildNode;
struct TreeNode *rightChildNode;
};
typedef struct TreeNode node;
node *rootNode = NULL;
/* Function to insert a node in a Binary search tree */
void insertNode(int i, node **n) {
if (*n == NULL) {
(*n) = (node*)malloc(sizeof(node));
(*n)->leftChildNode = NULL;
(*n)->rightChildNode = NULL;
(*n)->data = i;
}
else if ((*n)->data == i)
printf("\nThis value already exists in the tree!");
else if (i > (*n)->data)
insertNode(i, &((*n)->rightChildNode));
else
insertNode(i, &((*n)->leftChildNode));
}
/* End of insertNode() */
/* Function to search an element in a Binary search tree */
void searchNode(int i, node **n) {
if (*n == NULL)
printf("\nValue does not exist in tree!");
else if((*n)->data == i)
printf("\nValue found!");
else if(i > (*n)->data)
searchNode(i, &((*n)->rightChildNode));
else
searchNode(i, &((*n)->leftChildNode));
}
/* End of serachNode() */
/* The main() program begins */
int main()
{
int ch, num, num1;
do {
printf("\nSelect a choice from the menu below.");
printf("\n1. Insert a node.");
printf("\n2. Search for a node.");
printf("\nChoice: ");
scanf("%d", &ch);
switch(ch) {
case 1:
printf("\nEnter an element: ");
scanf("%d", &num);
insertNode(num, &rootNode);
break;
case 2:
printf("\nEnter the element to be searched for: ");
scanf("%d", &num);
searchNode(num, &rootNode);
break;
default:
exit(0);
}
printf("\nIf you want to return to the menu, press 1.");
printf("\nChoice: ");
scanf("%d", &num);
} while(num == 1);
return 0;
}
$ gcc binarysearchtree.c $ a.out Select a choice from the menu below. 1. Insert a node. 2. Search for a node. Choice: 1 Enter an element: 65 If you want to return to the menu, press 1. Choice: 1 Select a choice from the menu below. 1. Insert a node. 2. Search for a node. Choice: 1 Enter an element: 21 If you want to return to the menu, press 1. Choice: 1 Select a choice from the menu below. 1. Insert a node. 2. Search for a node. Choice: 2 Enter the element to be searched for: 65 Value found! If you want to return to the menu, press 1. Choice: 2
Sanfoundry Global Education & Learning Series – 1000 C Algorithms.
advertisement
If you wish to look at all C Algorithms and Solutions, go to C Algorithms.
Related Posts:
- Practice Programming MCQs
- Check Computer Science Books
- Check Data Structure Books
- Practice Computer Science MCQs
- Check Programming Books