Is there a special reason why the answer to 15.5 is formatted with two nested while loops? it seems the outer loop will be broken as soon as you reach the LCA. I wrote my code with an if else statement within the while loop (with the same condition) as so:
public static Node lca(Node a, Node b, Node root) {
// orient the nodes so that a is the lesser node and b is the greater node
if (a.data > b.data) {
Node tmp = a;
a = b;
b = tmp;
}
Node trav = root;
while(trav.data < a.data || b.data > trav.data) {
if (trav.data < a.data) {
trav = trav.right;
}
else {
trav = trav.left;
}
}
return trav;
}
I’ve run it through a few test cases, and it seems to work, but I want to make sure the logic is solid. The loop works as the first part of the book solution (the if p.data < s.data) and the else condition
will move the node to its right child until the lca is reached, am i missing something?