783. Minimum Distance Between BST Nodes

Given a Binary Search Tree (BST) with the root node `root`, return the minimum difference between the values of any two different nodes in the tree.

Example :

``````Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array.

The given tree [4,2,6,1,3,null,null] is represented by the following diagram:

4
/   \
2      6
/ \
1   3

while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.
``````

Note:

1. The size of the BST will be between 2 and `100`.
2. The BST is always valid, each node’s value is an integer, and each node’s value is different.

``````class Solution {
public:
int minDiffInBST(TreeNode* root) {
int res = INT_MAX;
vector<int> v;
helper(root, v);
for (int i = 1; i < v.size(); ++i) {
res = min(res, v[i] - v[i - 1]);
}
return res;
}
void helper(TreeNode* node, vector<int>& vals) {
if (!node) return;
helper(node->left, vals);
vals.push_back(node->val);
helper(node->right, vals);
}
};
``````

``````class Solution {
public:
int minDiffInBST(TreeNode* root) {
int res = INT_MAX, pre = -1;
helper(root, pre, res);
return res;
}
void helper(TreeNode* node, int& pre, int& res) {
if (!node) return;
helper(node->left, pre, res);
if (pre != -1) res = min(res, node->val - pre);
pre = node->val;
helper(node->right, pre, res);
}
};
``````

``````class Solution {
public:
int minDiffInBST(TreeNode* root) {
int res = INT_MAX;
helper(root, INT_MIN, INT_MAX, res);
return res;
}
void helper(TreeNode* node, int low, int high, int& res) {
if (!node) return;
if (low != INT_MIN) res = min(res, node->val - low);
if (high != INT_MAX) res = min(res, high - node->val);
helper(node->left, low, node->val, res);
helper(node->right, node->val, high, res);
}
};
``````

``````class Solution {
public:
int minDiffInBST(TreeNode* root) {
int res = INT_MAX, pre = -1;
stack<TreeNode*> st;
TreeNode* p = root;
while (!st.empty() || p) {
if (p) {
st.push(p);
p = p->left;
} else {
p = st.top(); st.pop();
if (pre != -1) res = min(res, p->val - pre);
pre = p->val;
p = p->right;
}
}
return res;
}
};
``````

Minimum Absolute Difference in BST

Binary Tree Inorder Traversal

https://leetcode.com/problems/minimum-distance-between-bst-nodes/solution/

https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/114834/Inorder-Traversal-O(N)-time-Recursion-C++JavaPython

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation