I'm having trouble writing code to determine if certain data is present in my tree, this is the BinaryTreeNode class
class BinaryTreeNode {
public:
Data * nodeData;
BinaryTreeNode * left;
BinaryTreeNode * right;
the function I need to complete is (can't change this definition)
bool BinaryTreeNode::member(Data * data) const {
I've tried to create a variable like currentnode = this and use a while loop to check which side of the tree to progress down, then update currentnode, but I can't seem to get that to work. So I'm thinking maybe it is supposed to be accomplished with recursion? I've tried that but the program locks up.
If anyone could point me into the right direction it would be extremely helpful.
Here's one of my many attempts (this one trying recursion):
bool BinaryTreeNode::member(Data * data) const {
if(nodeData == NULL) {
return false;
}
else if (nodeData->compareTo(data) == 0) {
return true;
}
while(this != NULL) {
if(nodeData->compareTo(data) == 0) {
return true;
}
else if(nodeData->compareTo(data) == 1) {
return left->member(data);
}
else if(nodeData->compareTo(data) == -1) {
return right->member(data);
}
}
return false;
}
while(this != NULL)
In the first call to that function, this
will never change to NULL
.
You can outright remove that one line. Then, just check for NULL
in your two branches.
if(left && nodeData->compareTo(data) == 1) {
return left->member(data);
}
if(right && nodeData->compareTo(data) == -1) {
return right->member(data);
}
Once you've recursively checked the left and right trees, you're done.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.