Binary Search Tree key/value pair - I know the value but not the key C++

algorithm, binary-search-tree, c++, data-structures, key-value

Solution

You can not take advantage of the fact that the tree is binary search tree if you want to search by value instead of key. So you have no other option but to iterate over the whole tree using BFS for instance.

Problem

I have a simple question that I am confused about. I know what is the concept of having a key/value pair in a Binary Search Tree and how the tree looks like when it is built. What I am unsure is of how to search for a value in such a BST if I have no track of what its key would be? For example: Let say I have a binary search tree full of integers (as values) and also unique integers (as keys). And let say I want to count the number of times a specific integer (lets say: 200) occurs in this BST. So what I know, 200 is the "value" and not the "key". Hence I dont know the key at all. How can I search now for all the "200"s in the whole BST? Does it become a simple BST now and I dont need the key at all? But again, the tree is arranged to the left child and the right child using the "key" and not the value. I can also give you a code sample of how I initialize the BST: ``` void insertNode(TreeNode *&p, int key, int value) { if (p == NULL) { p = new TreeNode; p->key = key; p->value = value; p->left = NULL; p->right = NULL; return; } if (key < p->key) insertNode(p->left, key, value); else insertNode(p->right, key, value); } ``` Any help would be appreciated.

Original source