I posted a question related to this topic earlier, but I’m having trouble figuring this out as well. I’m trying to search an unordered binary tree by a key value and return its associated value through a recursive function.
The class has the form:
Class Node
{
private:
Node *leftChild;
Node *rightChild;
int key;
int value;
}
With each variable having associated get methods. So I basically want to search through the binary tree and return its value once I get to the correct Node.
Here is my attempt thus far, I think I’m pretty close:
int preOrder(Node *node, int key)
{
if(node->getKey() == key)
return node->getValue();
Node* leftNode = node->getLeft();
if(leftNode != NULL)
{
return preOrder(leftNode, key);
}
Node* rightNode = node->getRight();
if(rightNode != NULL)
{
return preOrder(rightNode, key);
}
//I know a return statement needs to be placed here
//in case both pointers are NULL in order to return to the previous
//node in the tree, but I'm not sure how to do this...
}
Does anyone have any advice?
Here you go. This includes the code to answer your last question, modified to support Key/Value nodes instead of just Value nodes. Also, with the changes it made sense to return a pointer to the node rather than the value it contained, so I updated lowest to do it that way as well.
Look at example output: http://ideone.com/l5ZNc