I've got the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
branch* branch::find(string word)
{
if (word.compare(_word) == 0)
return this;
else
{
if (_left != 0 && _right != 0)
{
if (word.compare(_word) < 0)
{
if (_left != 0)
{
_left->find(word);
}
}
if (_right != 0)
{
if (word.compare(_word) > 0)
{
if (_right != 0)
{
_right->find(word);
}
}
}
if (word.compare(_word) == 0)
return this;
else
return 0;
}
else if (_right == 0 && _left != 0)
{
_left->find(word);
}
else if (_left == 0 && _right != 0)
{
_right->find(word);
}
else
if (word.compare(_word) == 0)
return this;
else
return 0;
}
}
|
My goal for this function is to return "this" (and
only "this") if the word which the user searches for is being found and to return 0 if the word which the user searches for is not being found.
_word is the root of the binary tree, _left en _right are pointers from the root.
I attempt to search the tree by comparing the strings (the word the user searches for and the word that is being referred to by one of the three pointers) compare. That way you know how to travel through the tree.
My problem: once the word has been found and "this" has been returned the program finishes the other instances that are on the stack (hopefully I phrase this correctly) and it ends with returning 0 unless it happens to be that the first word in the tree (_word) happens to be the word that is being searched (becausee in that case noting else is on the stack thus "this" is the last value which is being returned).
Question: how do I make sure that once I return "this" there will not be returned a 0 and that if the last string-comparison never equals 0 a 0 will be returned?
I want to do this whith returning a pointer to another class of the program, not whithin a single file (I know how to do that).
There is also still some flawed logic in it. Loading a new instance of this function with the first
_right -> find(word);
doesn't seem to work.