AfterAcademy Tech
•
06 Jun 2020

Difficulty: Easy
Asked in: Google
Given a BST(Binary Search Tree) with non-negative values, write a program to find the minimum absolute difference between values of any two nodes. Your answer should be the minimum difference possible taking any pair of nodes into account.
Possible questions to ask the interviewer:
For Example: →
Input: Given Binary Search Tree
7
/ \
3 10
/ \ / \
2 5 8 12
Output: 1
Explanation: The minimum absolute difference between any pair of nodes in this tree is 1, which is the difference between the nodes (3,2) and (8,7).
Input: Given Binary Search Tree
10
/ \
7 16
/ \ / \
5 8 12 20
Output: 2
Explanation: Here, the minimum absolute difference possible between any two pair is 2 from nodes (10,8).
Before we discuss the solution, you may want to give it a try. Try this problem here.
Solution idea
The idea of the solution is to use inorder traversal of the binary search tree. As you must already know, inorder traversal of a binary search tree gives us the elements in sorted order.
Once we have the elements in sorted order, we can find the minimum absolute difference by comparing adjacent elements of the list and finding the difference.
Solution steps
Pseudo-code
void inorder(TreeNode root, int[] A)
{
if(root == NULL)
return;
inorder(root->left, A)
A.add(root->val) //adding elements
inorder(root->right, A)
}
int getMinimumAbsDiff(TreeNode root) {
int [] arr
int min_so_far = INT_MAX // max int value possible
inorder(root, A)
for(int i=0 to A.length -1 ; i=i+1)
{
if ((A[i+1] - A[i]) < min_so_far)
min_so_far = A[i+1] - A[i]
}
return min_so_far
}
Complexity Analysis
Time Complexity: O(N)
Space Complexity: O(N) (Why?)
Critical ideas to think!
If you have any feedback or a better approach to this problem, please write down in the comment section below.
Happy Coding!
AfterAcademy Tech
Given an array of distinct integers A[ ], write a program to find all pairs of elements with the minimum absolute difference of any two elements.

AfterAcademy Tech
This is a famous interview problem based on dynamic Programming. This question has been asked in big companies like Amazon. Here we need to find the path between the given source and destination that gives the minimum cost.

AfterAcademy Tech
This is an interview problem based on the concept of dynamic programming. This question has been asked in various companies. We are dealing with solutions based on recursion, memorization and dynamic programming.

AfterAcademy Tech
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
