Google Interview Question
1,069 Interview Reviews |
Back to all Google Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Engineer at Google:
You're given a binary tree and pointers to two nodes in the tree. Describe the fastest algorithm you can come up with to determine the closest common ancestor.
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (4)
//return 0 - none found, 1 - a found, 2 - b found, 3 - both found
public int modifiedDFS(Node node, Node a, Node b, int ) {
int res=0;
if (node) {
if ((node.left == a) || (node.right == a)) {
res += 1;
}
if ((node.left == b) || (node.right == b)) {
res += 2;
}
if (res == 3) {
lowest = node;
} else {
int l = modifiedDFS(node.right, a, b);
int r = modifiedDFS(node.left, a, b);
if ((l==3) || (r==3)) {
//lower node is the one
res = 3;
} else {
if ((3 == (l+r)) ||
(3 == (l+res)) ||
(3 == (r+res)) {
//i am the lowest
lowest = node;
res = 3;
} else {
if ((l==1)||(r==1))
res = 1;
if ((2==l)||(2==r))
res = 2;
}
}
}
}
return res;
}
Helpful Answer?
Yes |
No
Inappropriate?
Remember: you're given a pointer to the nodes in question. To traverse from a leaf node to the root is worst-case O(lg n) operations. Think of something you could do to take advantage of that.
Helpful Answer?
Yes |
No
Inappropriate?
If there is no parent pointer, I'd use tree traversal (pre-, in-, or post- doesn't matter much). The closest common ancestor would be the only node that find one node on its left children (or itself) and the other node on its right children (or itself). This is O(n).
Helpful Answer?
Yes |
No
Inappropriate?
Members can
answer or comment on this question
–
Join Now (It's Free) or
Sign In
0 of 0 people found this helpful
by Interview Candidate: