C++ Program to Find the Number of occurrences of a given Number using Binary Search approach

C++ Program to find the number of occurrences of a given number using binary search approach.

Problem Description

1. Implement binary search tree to find the number of occurrences of a given number.
2. The worst case time complexity of Binary search is O(n) but for the average case, it is O(log(n)).

Problem Solution

1. Construct binary search tree for the given unsorted data array and maintain an additional count variable.
2. If any element is repeated then increase the count of that node.
3. Proceed with the search by comparing an element to the data of the node and print the count of that particular data element.
4. Exit.

Program/Source Code

C++ program to count the number of occurrences of a given number using binary search approach.
This program is successfully run on Dev-C++ using TDM-GCC 4.9.2 MinGW compiler on a Windows system.

1. Construct binary search tree for the given unsorted data array by inserting data into tree one by one, using InsertIntoTree().
2. In the node structure, maintain an additional count variable for each node.
3. Inside InsertIntoTree(), compare the data with data part of the node.
4. If this node is null, then insert the new node.
5. If data = temp->data, increase the count of that particular node.
6. If data < temp->data, move the temp pointer to the left child.
7. If data > temp->data, move the temp pointer to the right child.
8. Take the input of data to be searched in the BST.
9. Starting from the root node, compare the data with data part of the node.
10. If data < temp->data, move the temp pointer to the left child.
11. If data > temp->data, move the temp pointer to the right child.
12. If data = temp->data, print the item found and it’s count and then, return to main.
13. Else print data not found.
14. Ask user if he wants to search more, if yes, repeat from 10.
15. Exit.

Runtime Test Cases

Case 1:
Enter the Element to be searched: 89
Data item 89 is present 4 number of times.
Do you want to search more...enter choice(y/n)?y
Enter the Element to be searched: 27
Data item 27 is present 1 number of times.
Do you want to search more...enter choice(y/n)?y
Enter the Element to be searched: 72
Data item 72 is present 2 number of times.
Do you want to search more...enter choice(y/n)?y
Enter the Element to be searched: 28
Data not found
Do you want to search more...enter choice(y/n)?n