Given a binary search tree of size N > 1, the task is to find the minimum absolute difference between any two nodes.
Input: 5 / \ 3 7 / \ / \ 2 4 6 8 Output: 1 Difference between all the consecutive nodes if sorted is 1. Thus, the answer is 1. Input: 1 \ 6 Output: 5
Approach: We know that in-order traversal of a Binary Search Tree traverses it in sorted order. So, for every node, we will find its difference from the previous node in the in-order traversal of the tree. If this difference is smaller than the previous minimum difference, we will update the previous minimum difference. Following are the steps to follow:
- Create a variable ‘prev’ to store the pointer to the previous node in in-order traversal.
- Create a variable ‘ans’ to store the minimum difference.
- For every node in the in-order traversal, compare its absolute difference with the previous node and update the minimum absolute difference found so far.
Below is the implementation of the above approach:
Another Approach with O(1) Space Complexity:
Time complexity: O(N)
Additional Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the minimum absolute difference in two different BST's
- Pair with minimum absolute difference after solving each query
- Find k-th smallest element in BST (Order Statistics in BST)
- Two nodes of a BST are swapped, correct the BST
- K'th Largest Element in BST when modification to BST is not allowed
- Convert a normal BST to Balanced BST
- Two nodes of a BST are swapped, correct the BST | Set-2
- Longest subsequence such that absolute difference between every pair is atmost 1
- Find a pair with given sum in a Balanced BST
- Find a pair with given sum in BST
- Pair with a given sum in BST | Set 2
- Find the node whose absolute difference with X gives minimum value
- Find the node whose absolute difference with X gives maximum value
- Sort an array according to absolute difference with given value using Functors
- Maximum absolute difference between any two level sum in a Binary Tree
- Last element remaining by deleting two largest elements and replacing by their absolute difference if they are unequal
- Find K elements whose absolute difference with median of array is maximum
- Maximum absolute difference between any two level sum in a N-ary Tree
- Maximum absolute difference between distinct elements in an Array
- A program to check if a binary tree is BST or not
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.