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)
- Pair with minimum absolute difference after solving each query
- Find the minimum absolute difference in two different BST's
- Find the node whose absolute difference with X gives minimum value
- Sort an array according to absolute difference with given value using Functors
- Find the node whose absolute difference with X gives maximum value
- Queries to add, remove and return the difference of maximum and minimum.
- Sub-tree with minimum color difference in a 2-coloured tree
- Pair with a given sum in BST | Set 2
- Find a pair with given sum in BST
- Stack of Pair in C++ STL with Examples
- Find a pair with given sum in a Balanced BST
- Construct an array from its pair-product
- Find count of pair of nodes at even distance
- Find pairs with given sum such that pair elements lie in different BSTs
- Find the number of pair of Ideal nodes in a given tree
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.