C Program to Search an Element in a Tree Recursively

This is a C Program to search an element in a Binary Search Tree recursively.

Problem Description

We have to write a C program to search an element(node) in a Binary Search Tree recursively.

Expected Input and Output

Case 1. Balanced Tree:When the weight is equal on both the sides of root.

If the input tree is              
                    25
                  /    \  
                 17     35   
                / \     / \ 
              13  19   27 55 
and the key to be searched for is 15,
then the output will be : Key not found.

Case 2. Right Skewed Tree:When the nodes at every level just have a right child.

If the input tree is
                    1   
                     \
                      2    
                       \    
                        3 
                         \
                          4
                           \
                            5
and the key to be searched for is 4,
then the output will be : Key found in tree.

Case 3. Tree having just one node

advertisement
advertisement
If the input tree is
                15
and the key to be searched for is 15,
then the output will be : Key found in tree.
Problem Solution

We can easily find the element in a BST if it exists.
1. If the key is greater than the root node of the tree, it will lie in right subtree.
2. If it key is smaller than the root node of the tree, it will lie in the left subtree.

Program/Source Code

Here is source code of the C Program for searching a node or an element in a Binary Search Tree. The program is successfully compiled and tested using Codeblocks gnu/GCC compiler on windows 10. The program output is also shown below.

  1. /*
  2.  * C Program to search an element in a Binary Search Tree
  3.  */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. struct node
  7. {
  8.     int info;
  9.     struct node *left, *right;
  10. };
  11. struct node *createnode(int key)
  12. {
  13.     struct node *newnode = (struct node*)malloc(sizeof(struct node));
  14.     newnode->info = key;
  15.     newnode->left = NULL;
  16.     newnode->right = NULL;
  17.     return(newnode);
  18. }
  19. int search(struct node *head, int key)
  20. {
  21.     while (head != NULL)
  22.     {
  23.         if (key > head->info)
  24.         {
  25.             return search(head->right, key);
  26.         }
  27.         else if (key < head->info)
  28.         {
  29.             return search(head->left, key);
  30.         }
  31.         else
  32.         {
  33.             return 1;
  34.         }
  35.     }
  36.     return 0;
  37. }
  38. /*
  39.  * Main Function
  40.  */
  41. int main()
  42. {
  43.     int flag = 0;
  44.     /* Creating first Tree. */
  45.     struct node *newnode = createnode(25);
  46.     newnode->left = createnode(17);
  47.     newnode->right = createnode(35);
  48.     newnode->left->left = createnode(13);
  49.     newnode->left->right = createnode(19);
  50.     newnode->right->left = createnode(27);
  51.     newnode->right->right = createnode(55);
  52.     /* Sample Tree 1:
  53.      *               25
  54.      *             /    \
  55.      *            17     35
  56.      *           / \     / \
  57.      *         13  19   27 55
  58.      */
  59.     flag = search(newnode,15);
  60.     if (flag)
  61.     {
  62.         printf("Key %d found in tree 1 \n", 15);
  63.     }
  64.     else
  65.     {
  66.         printf("Key %d not found in tree 1\n", 15);
  67.     }
  68.  
  69.     /* Creating second Tree. */
  70.     struct node *node = createnode(1);
  71.     node->right = createnode(2);
  72.     node->right->right = createnode(3);
  73.     node->right->right->right = createnode(4);
  74.     node->right->right->right->right = createnode(5);
  75.     /* Sample Tree 2:   Right Skewed Tree (Unbalanced).
  76.      *               1
  77.      *                \
  78.      *                 2
  79.      *                  \
  80.      *                   3
  81.      *                    \
  82.      *                     4
  83.      *                      \
  84.      *                       5
  85.      */
  86.     flag = search(node,4);
  87.     if (flag)
  88.     {
  89.         printf("Key %d found in tree 2\n", 4);
  90.     }
  91.     else
  92.     {
  93.         printf("Key %d not found in tree 2\n", 4);
  94.     }
  95.  
  96.     /* Creating third Tree. */
  97.     struct node *root = createnode(15);
  98.     /* Sample Tree 3- Tree having just one root node.
  99.      *              15
  100.      */
  101.     flag = search(root,15);
  102.     if (flag)
  103.     {
  104.         printf("Key %d found in tree 3 \n", 15);
  105.     }
  106.     else
  107.     {
  108.        	printf("Key %d not found in tree 3\n", 15);
  109.     }
  110.     return 0;
  111. }
Program Explanation

1. Here in the above program we have written a function search(struct node *head, int key), which is taking in two parameters the root node of tree and the key which is to be searched in tree.
2. In order to search for an element in a BST we compare it with each and every node in tree so that we can decide whether to follow the left or the right child of that node.
3. We start with the root node, we compare the key with the root node i.e. head of the tree, if the key is less than the root node, we start searching in left subtree i.e we compare the key with the left child of root node, and so on.
4. Similarly if the key is greater than the root node, we start searching in right subtree i.e. we compare key with the right child of root node and so on recursively.
5. If we are able to find the element we print “Key found in tree” else we print “Key not found”.

advertisement
Runtime Test Cases
Key 15 not found in tree 1
Key 4 found in tree 2
Key 15 found in tree 3

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

advertisement
If you wish to look at other example programs on Trees, go to Trees. If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.