You have been given a Binary Search Tree and two keys 'NODE1' and 'Node2' in it.
Your task is to find the shortest distance between two nodes with the given two keys. It may be assumed that both keys exist in BST.
Example:
For the above BST:
‘NODE1’ = 6, ‘NODE2’ = 14
Distance between 6 and 14 = (Number of nodes in the path from 6 to 14) + 1.
So the path from 6 to 14 is : ( 6 -> 3 -> 8 -> 10 -> 14).
Distance between 6 and 14 = 3 ( i.e. 3, 8, 10 are in path) + 1 = 4.
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases. Then each test case follows.
The first line of input contains the elements of the tree in the level order form separated by a single space.
If any node does not have a left or right child, take -1 in its place. Refer to the example below.
The second line of each test case contains two space-separated integers, ‘NODE1’ and ‘NODE2’, denoting the keys of the two given nodes.
Example:
Elements are in the level order form. The input consists of values of nodes separated by a single space in a single line. In case a node is null, we take -1 in its place.
For example, the input for the tree (not a BST) depicted in the below image would be :
1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1
Explanation :
Level 1 :
The root node of the tree is 1
Level 2 :
Left child of 1 = 2
Right child of 1 = 3
Level 3 :
Left child of 2 = 4
Right child of 2 = null (-1)
Left child of 3 = 5
Right child of 3 = 6
Level 4 :
Left child of 4 = null (-1)
Right child of 4 = 7
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 6 = null (-1)
Right child of 6 = null (-1)
Level 5 :
Left child of 7 = null (-1)
Right child of 7 = null (-1)
The first not-null node (of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.
The input ends when all nodes at the last level are null (-1).
Output Format:
For each test case, return an integer denoting the distance between two keys, i.e., ‘NODE1’ and ‘NODE2’ in the given BST.
Note:
You do not need to print anything; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 10^2
1 <= N <= 10^3
1 <= Node.data <= 10^9
Where 'N' denotes the number of nodes in the BST and 'Node.data' represents the keys of nodes in BST.
The keys ‘NODE1’ and ‘NODE2’ are present in the given BST.
Time Limit: 1 sec
I directly gave an approach to find the lowest common ancestor of the two nodes and then finding separate distances between the Ancestor node and the two nodes and returning the sum of the distances. ...read more
Lowest common ancestor: Let ‘T’ be a rooted tree. The lowest common ancestor of the two nodes, ‘NODE1’ and ‘NODE2’, is the lowest node in ‘T’ with both ‘NODE1’ and ‘NODE2’ as its descendants (here, a node can be a descendant of itself).
We store the path from ‘ROOT’ to ‘NODE1’ in ‘PATH1’ and ‘ROOT’ to ‘NODE2’ in ‘PATH2’. Iterate the arrays ‘PATH1’ and ‘PATH2’ until they have the same values, the LCA will be the node just before the mismatch. The following function finds the path from ‘ROOT’ to the node with the given ‘KEY’ and stores it in the array ‘PATH’ (passed by reference).
‘Boolean pathFromRoot(BinaryTreeNode ROOT, array PATH, integer KEY)’:
- If ‘ROOT’ is ‘NULL’, then:
- Return ‘FALSE’ (Base condition).
- ‘path.append(ROOT->DATA)’. Append the key at the ‘ROOT’ node to ‘PATH’.
- If ‘ROOT->DATA’ is equal to ‘KEY’, then we can stop the search for ‘KEY’:
- Return ‘TRUE’.
- If (‘pathFromRoot(ROOT->LEFT, PATH, KEY)’ is ‘TRUE’) or (‘pathFromRoot(ROOT->RIGHT, PATH, KEY)’ is ‘TRUE’), then we can stop the search for ‘KEY’ as the subtree at ‘ROOT’ contains the node with the given ‘KEY’:
- Return ‘TRUE’.
- ‘path.pop_back()’. Remove the last element of ‘PATH’ (i.e., ‘ROOT->DATA’) as the node with given ‘KEY’ is not present in the subtree at ‘ROOT’.
- Return ‘FALSE’.
The shortest distance between ‘NODE1’ and ‘NODE2’ = (Distance from ‘LCA’ to ‘NODE1’) + (Distance from ‘LCA’ to ‘NODE2’).
ALGORITHM:
- Create two integer arrays ‘PATH1’ and ‘PATH2’ to store the path from ‘ROOT’ to ‘NODE1’ and ‘ROOT’ to ‘NODE2’, respectively.
- ‘pathFromRoot(ROOT, PATH1, NODE1)’. Store the path from ‘ROOT’ to ‘NODE1’ in the array ‘PATH1’.
- ‘pathFromRoot(ROOT, PATH2, NODE2)’. Store the path from ‘ROOT’ to ‘NODE2’ in the array ‘PATH2’.
- Set ‘i = 0’. Use it to find the first index where ‘PATH1’ and ‘PATH2’ are different.
- Run a loop until (‘i < PATH1.size()’) and (‘i < PATH2.size()’):
- If ‘PATH1[i]’ is not equal to ‘PATH2[i]’, then ‘i - 1’ is the index of the LCA of ‘NODE1’ and ‘NODE2’.:
- Break the loop.
- If ‘PATH1[i]’ is not equal to ‘PATH2[i]’, then ‘i - 1’ is the index of the LCA of ‘NODE1’ and ‘NODE2’.:
- Set ‘DIST1 = PATH1.size() - i’. This is the distance of ‘NODE1’ from ‘LCA’.
- Set ‘DIST2 = PATH2.size() - i’. This is the distance of ‘NODE2’ from ‘LCA’.
- Return ‘DIST1 + DIST2’ as the answer.
O(N), where ‘N’ is the number of nodes in the given BST.
The recursion stack used for the function ‘pathfromRoot’ stores ‘O(N)’ elements. The arrays ‘PATH1’ and ‘PATH2’ also store ‘O(N)’ elements. Thus, the space complexity is ‘O(N)’.
O(N), where ‘N’ is the number of nodes in the given BST.
To find the path from ‘ROOT’ to ‘NODE1’ and ‘ROOT’ to ‘NODE2’ we may have to traverse the entire BST. We traverse the arrays ‘PATH1’ and ‘PATH2’ which may store ‘O(N)’ elements. Thus, the time complexity is ‘O(N)’.
Java (SE 1.8)
/*
Time Complexity : O(N)
Space Complexity : O(N)
Where 'N' is the number of nodes in the given BST.
*/
import java.util.ArrayList;
public class Solution {
/*
Check if the subtree at 'root' contains the node with the given 'key' and
store the path from 'root' node to the node with the given 'key' in the array 'path'.
*/
public static boolean pathFromRoot(BinaryTreeNode root, ArrayList path, int key) {
if (root == null) {
return false;
}
// Append the key at 'root' node to 'path'.
path.add(root.data);
// Check if 'root' node has the given 'key'.
if (root.data == key) {
return true;
}
/*
Try to find the node with the given 'key' is in the left or
right sub-tree of 'root' and update 'path' accordingly.
*/
if (pathFromRoot(root.left, path, key) || pathFromRoot(root.right, path, key)) {
return true;
}
/*
If the node with the given 'key' doesn't lie in the subtree
at 'root', remove 'root' from the array 'path'.
*/
path.remove(path.size() - 1);
return false;
}
public static int distanceBetween2(BinaryTreeNode root, int node1, int node2) {
ArrayList path1 = new ArrayList<>();
ArrayList path2 = new ArrayList<>();
// Store the path from 'root' to 'node1' in the array 'path1'.
pathFromRoot(root, path1, node1);
// Store the path from 'root' to 'node1' in the array 'path1'.
pathFromRoot(root, path2, node2);
int i = 0;
// Compare 'path1' and 'path2' until we get the first different value.
for (; i < path1.size() && i < path2.size(); i++) {
if (path1.get(i) != path2.get(i)) {
// The node at postion 'i - 1' is the LCA of 'node1' and 'node2'.
break;
}
}
// Distance of 'node1' from LCA.
int dist1 = path1.size() - i;
// Distance of 'node2' from LCA.
int dist2 = path2.size() - i;
// Shortest distance between 'node1' and 'node2'.
return dist1 + dist2;
}
}
Python (3.5)
'''
Time Complexity : O(N)
Space Complexity : O(N)
where N is the number of nodes in the given BST.
'''
'''
Check if the subtree at 'root' contains the node with the given 'key' and
store the path from 'root' node to the node with the given 'key' in the array 'path'.
'''
def pathFromRoot(root, path, key):
if (not root):
return False
# Append the key at 'root' node to 'path'.
path.append(root.data)
# Check if 'root' node has the given 'key'.
if (root.data == key):
return True
'''
Try to find the node with the given 'key' is in the left or
right sub-tree of 'root' and update 'path' accordingly.
'''
if (pathFromRoot(root.left, path, key) or pathFromRoot(root.right, path, key)):
return True
'''
If the node with the given 'key' doesn't lie in the subtree
at 'root', remove 'root' from the array 'path'.
'''
path.pop()
return False
def distanceBetween2(root, node1, node2):
path1 = []
path2 = []
# Store the path from 'root' to 'node1' in the array 'path1'.
pathFromRoot(root, path1, node1)
# Store the path from 'root' to 'node1' in the array 'path1'.
pathFromRoot(root, path2, node2)
i = 0
# Compare 'path1' and 'path2' until we get the first different value.
while(i < len(path1) and i < len(path2)):
if (path1[i] != path2[i]):
# The node at postion 'i - 1' is the LCA of 'node1' and 'node2'.
break
i+=1
# Distance of 'node1' from LCA.
dist1 = len(path1) - i
# Distance of 'node2' from LCA.
dist2 = len(path2) - i
# Shortest distance between 'node1' and 'node2'.
return dist1 + dist2
C++ (g++ 5.4)
/*
Time Complexity : O(N)
Space Complexity : O(N)
where N is the number of nodes in the given BST.
*/
/*
Check if the subtree at 'root' contains the node with the given 'key' and
store the path from 'root' node to the node with the given 'key' in the array 'path'.
*/
bool pathFromRoot(BinaryTreeNode* root, vector& path, int key) {
if (!root) return false;
// Append the key at 'root' node to 'path'.
path.push_back(root->data);
// Check if 'root' node has the given 'key'.
if (root->data == key)
return true;
/*
Try to find the node with the given 'key' is in the left or
right sub-tree of 'root' and update 'path' accordingly.
*/
if (pathFromRoot(root->left, path, key) || pathFromRoot(root->right, path, key)) {
return true;
}
/*
If the node with the given 'key' doesn't lie in the subtree
at 'root', remove 'root' from the array 'path'.
*/
path.pop_back();
return false;
}
int distanceBetween2(BinaryTreeNode* root, int node1, int node2) {
vector path1, path2;
// Store the path from 'root' to 'node1' in the array 'path1'.
pathFromRoot(root, path1, node1);
// Store the path from 'root' to 'node1' in the array 'path1'.
pathFromRoot(root, path2, node2);
int i = 0;
// Compare 'path1' and 'path2' until we get the first different value.
for (; i < path1.size() && i < path2.size(); i++) {
if (path1[i] != path2[i]) {
// The node at postion 'i - 1' is the LCA of 'node1' and 'node2'.
break;
}
}
// Distance of 'node1' from LCA.
int dist1 = path1.size() - i;
// Distance of 'node2' from LCA.
int dist2 = path2.size() - i;
// Shortest distance between 'node1' and 'node2'.
return dist1 + dist2;
}
The shortest distance between ‘NODE1’ and ‘NODE2’ = (Distance from ‘LCA’ to ‘NODE1’) + (Distance from ‘LCA’ to ‘NODE2’).
The distance between an ancestor node(in this case, the ‘LCA’...read more
Top Blackrock Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in Blackrock Software Developer
Reviews
Interviews
Salaries
Users/Month