Amazon Interview Question
Country: United States
Interview Type: Phone Interview
one small addition: before looking for LCA by using the standard algorithm(find a node with a value that is greater than first node value and less than 2nd node value) check if node1.left = node2 or node1.right = node2 or node2.left = node1 or node2.right = node1 and return 1 if it is true
With languages that pass parameters with references like JAVA, your "root" variable will be changed after execution. Other than this, I think it is correct.
I'm afarid you are not right. Java passes objects as references passed by value. Should you modify, say, root.val, it will modify it indeed. Changing root won't do that.
I agree with @nitingupta180 , once you find the least common ancestor of two nodes , you need to find the distance from the first node to LCA and from LCA to second node, then add them up.
We can do a preorder traversal on the binary tree.
Time compexity O(N), space complexity, O(log(n))
int findDistance(const Node * root, int val1, int val2)
{
// check if the tree is empty or not
if(root == NULL)
{
std::cout<<"Empty tree" << std::endl;
return -1;
}
// check if the two values are equal or not, if they are
// then the distance between the two is obviously zero
if(val1 == val2)
return 0;
// have a stack to hold the nodes for back traversal
std::stack<Node*> stack;
// For simplifying our code, we will make val1 < val2
if(val2 < val1)
{
val1 = val1 + val2;
val2 = val1 - val2;
val1 = val1 - val2;
}
// initial distance betwen nodes is -1
int distance = -1;
while(!stack.empty() || root != null)
{
// traverse to the left of the subtree at root
if(root != null)
{
if(root->val == val1)
distance = 0;
// if value of this node = val2, then we are done
// return distance calculated so far
else if(root->val == val2)
return distance;
stack.push(root);
root = root->left;
// this node might be on the path between val and val2
// increment distance
++distance;
}
// else go right
else
{
root = stack.pop();
// this node is not on the path between val and val2
// decrement distance
--distance;
root = root->right;
}
}
return distance;
}
Please let me know if I have missed any corner case or if the logic needs some change
Hey abhishek
What is use of this code to exchange the value of val1 and val2 ?
if(val2 < val1)
{
val1 = val1 + val2;
val2 = val1 - val2;
val1 = val1 - val2;
}
We can read these values as per our convince.
Another thing is that , i don't think so it will give required result.
It would be great if you explain with some example.
Find least common ancestor of two nodes, then you can find distance between them.
- Nitin Gupta February 07, 2013