GeeksforGeeks » Interview Questions
Amazon Interview Question for Software Engineer/Developer about Trees
(4 posts)-
Given two nodes of a BST and all elements in BST are distinct, write code to determine the shortest distance between the two nodes. (unit distance between two adjacent nodes). Nodes dont have parent pointer.
-
@freakCoder, May we use level-order traversal? Thank you.
-
Algo->
1->find LCA of the 2 nodes
2-> min distance between nodes= distance(LCA,a) + distance(LCA,b)Edge case-> If one of the node itself is the LCA,then min distance is the distance of other node from LCA
-
@freakCoder, Here is an alternative solution to iCodeS's solution. Thank you.
struct node {
int data;
struct node *left;
struct node *right;
};//modified prandeev's code
void getLevelUtil(struct node* data1, struct node* data2,
int level , int& retval) {
if ( data1 == NULL || data2 == NULL ){
return;
}
if ( data1->data == data2->data){
retval = level;
return;
}getLevelUtil ( data1->left, data2, level+1, retval);
getLevelUtil ( data1->right, data2, level+1, retval);}
bool PathExistsUtil(struct node *node1, struct node *node2){
if (node1 == NULL || node2 == NULL){
return false;
}
if (node1 == node2){
return true;
}
return PathExistsUtil(node1->left,node2) || PathExistsUtil(node1->right,node2);}
bool PathExists(struct node *node1, struct node *node2){
if (node1->data <= node2->data){
return PathExistsUtil(node2, node1);
}
else{
return PathExistsUtil(node1, node2);
}
}int FindLevelDifference(struct node* node1, struct node* node2){
int retval(-1000000);
if (PathExists(node1,node2) == false){
return -1;
}
else{
if (node1->data <= node2->data){
getLevelUtil(node2, node1, 0, retval);
}
else{
getLevelUtil(node1, node2, 0, retval);
}
return retval;
}
}
Reply
You must log in to post.