Google Interview Question

Find the least common root for 2 numbers in a BST

Interview Answers

Anonymous

Dec 7, 2010

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

Anonymous

Dec 12, 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; }

1

Anonymous

Oct 19, 2010

Node FindCommonRoot(root,x,y) { if(!root) return NULL if((root->value value right,x,y) else if((root->value > x) && (root->value > y)) return FindCommonRoot(root->left,x,y) else if(((root->value > x) && (root->value value value > y))) return root }

1

Anonymous

Dec 14, 2010

@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.

Anonymous

Nov 9, 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; }

1