Minimum Absolute Difference in BST
Problem
Given the root
of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
Constraints
- The number of nodes in the tree is in the range
[2, 104]
. 0 <= Node.val <= 105
Solution
The problem Minimum Absolute Difference in BST
can be solved using an inorder traversal. When a binary search tree is traversed inorder, its elements are sorted in ascending order. Therefore, minimum absolute difference can be found by comparing differences between consecutive nodes.
Implementation
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
int getMinimumDifference(TreeNode *root)
{
int prev = INT_MAX;
int diff = INT_MAX;
stack<TreeNode *> nodes;
while (!(nodes.empty() && root == NULL))
{
while (root != NULL)
{
nodes.push(root);
root = root->left;
}
root = nodes.top();
nodes.pop();
diff = min(diff, abs(root->val - prev));
prev = root->val;
root = root->right;
}
return diff;
}
};