Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
Find the LCA of the two nodes.
- If the LCA is the root, then it means that both the nodes have unique path to the root. Print both the paths.
- Else, it means that the nodes have unique path till the LCA node. Print the paths for each of these nodes till the LCA
Hi Anonymous ... This is a good approach in my opinion. Just want to confirm that to find the LCA, if the tree is not a BST and just a binary tree, we have to store the nodes traversed in respective arrays for both the first node and the second node and then find the LCA by finding the common path based on the 2 arrays ... am I right
First store a pointer to first node. Then keep traversing the first node's parent till we hit the root. Note whether we encounter the second node along the way with the "encountered" variable. If we encountered the second node along the way, then we already printed the path from the second node to the root. Otherwise, keep traversing the second node's parent pointer till we either hit the root or encounter the original first node along the way. Advantage of this is that we only traverse both paths once, and we aren't using any additional data structure.
(Didn't really test this code though)
static void findRoot(Node n, Node n2) {
boolean encountered = false;
Node tmp = n;
System.out.println("FIRST");
while(n != null) {
if(n == n2)
encountered = true;
System.out.println(n.value);
n = n.parent;
}
System.out.println("SECOND");
while(!encountered && n2 != null) {
System.out.println(n2.value);
n2 = n2.parent;
if(n2 == tmp)
encountered = true;
}
}
I really do not understand what is the meaning of printing path here. My understanding is printing the value or the node pointer.
if so code goes here
printpath(node * node1, node* node2)
{
if(node1 == NULL || node2 == NULL)
{// reached parent
return;
}
if(node1 == node2)
{
// now both the nodes have same parent so stop printing
return;
}
print node1;
print node2;
printpath(node1-> parent, node2->parent);
}
- Consider the two paths as two linked lists
- find the length of both the lists and get the difference in length
- move the pointer of longer list by the difference and add every node to the path
- move pointers to both the lists till they meet and add nodes to respective paths
- if the meeting point is root add root to both the paths
- display the paths
- learner January 03, 2013