How to find all the elements in an ordered dictionary implemented as a binary tree that has the key k

advertisements

Given a binary tree I need to implement a method findAllElements(k) to find all the elements in the tree with a key equal to k.

The idea I had is the first time you come across an element with key k. All the elements with the same key should be either in the left child's right subtree or the right child's left subtree. But I was told this may not be the case?

I just need to find a way to implement an algorithm. So pseudo code is needed.

I probably should have added this sorry. But the implementation is that the left subtree contains keys less than or equal to the key at the root and the right subtree contains keys greater than or equal to the key at the root.


Look at the current node. If its key is higher than k, search the left subtree. If it is lower, search the right subtree. If it is equal, search both left and right subtrees (and also include the current node in the results).

Do that recursively starting from the root node.