Amazon.com Interview Question
1,572 Interview Reviews |
Back to all Amazon.com Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Development Engineer at Amazon.com:
Given a binary tree with the usual left and right pointers on each node, and additionally a parent pointer, make an algorithm to discover the closest ancestor to 2 nodes on the tree.
See more for this Amazon.com Software Development Engineer Interview
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (6)
Helpful Answer?
Yes |
No
Inappropriate?
what do you mean by incomplete? Can you be more precise?.
Common ancestor - first encounter of node value between a and b. Otherwise either you go left or right node.
Helpful Answer?
Yes |
No
Inappropriate?
Helpful Answer?
Yes |
No
Inappropriate?
2 of 2 people found this helpful
1) Find matching node for the first value in the tree. If the node found create a set contains all its parents till the root.
2) Use postorder traversal for recording all the ancestor.
3) P1 is parent, P2 is grand parent and P3 is ggparent and continue till root.
V1={P1,P2,P3,P4,....root}
4) Similary find all the parent of second value
V2={P1,P2,P3,.root}.
5) traverse both set and first matching element in both sets is lowest common ancestor.
Helpful Answer?
Yes |
No
Inappropriate?
1 of 1 people found this helpful
Complexity - O( 3 lg N)
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up



1 of 1 people found this helpful
by analog76:
public void findCommonAncestor(Node current,int a,int b){
if(current.getKey() <a && current.getKey()<b)
findCommonAncestor(current.getRight(),a,b);
else if (current.getKey()>a && current.getKey()>b){
findCommonAncestor(current.getLeft(), a, b);
}else{
System.out.println(" least common ancestor is "+current.getKey());
}
}