783. Minimum Distance Between BST Nodes
Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
Example 1:
Input: root = [4,2,6,1,3]
Output: 1
Example 2:
Input: root = [1,0,48,null,null,12,49]
Output: 1
Constraints:
- The number of nodes in the tree is in the range [2, 100].
- 0 < = N o d e . v a l < = 1 0 5 0 <= Node.val <= 10^5 0<=Node.val<=105
From: LeetCode
Link: 783. Minimum Distance Between BST Nodes
Solution:
Ideas:
-
In-order traversal visits nodes in ascending order for BST.
-
prev tracks the previously visited node value.
-
minDiff stores the current smallest difference.
Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
// Helper function for in-order traversal
void inorder(struct TreeNode* root, int* prev, int* minDiff) {
if (!root) return;
inorder(root->left, prev, minDiff);
if (*prev != -1) {
int diff = root->val - *prev;
if (diff < *minDiff) {
*minDiff = diff;
}
}
*prev = root->val;
inorder(root->right, prev, minDiff);
}
int minDiffInBST(struct TreeNode* root) {
int prev = -1;
int minDiff = INT_MAX;
inorder(root, &prev, &minDiff);
return minDiff;
}