Dear Lamont,
You need another "else" statement which should return runner. Otherwise there will be an infinite loop in some cases (when one of x or y is equal to the current root).
3
Sigiloso
12 de dez. de 2010
Here's a Java version:
// This method is in BSTNode class
BSTNode findLowestCommonAnsector(int va1, int val2) {
BSTNode root = this;
while(root != null) {
int val =root.value;
if(val > val1 && val > val2)
root = root.left;
else if(val < val1 && val < val2)
root = root.right;
else
return root;
}
return null;
}
@Aytekin - D'oh! This code originally had an "else break" but I failed to type it in here. It's not like this is a special case. This is what happens when we find the common root and want to return it.
The top solution (Tal) has a similar problem. If x or y equals the current value, the function falls off the end without returning anything. I was trying to improve upon it and ended up making a bigger mistake. Sorry, folks.
Sigiloso
9 de nov. de 2010
Node *Tree::LeastCommonRoot(x, y)
{
Node *runner = this->root;
while (runner)
if (x value && y value)
runner = runner->left;
else if (x > runner->value && y > runner->value)
runner = runner->right;
return runner;
}