给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/
/**
* 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 ans = INT_MAX;
int pre = -1;
void dfs(TreeNode* root) {
if (!root) {
return;
}
dfs(root->left);
if (pre == -1){
pre = root->val;
}
else {
ans = min(ans, root->val - pre);
pre = root->val;
}
dfs(root->right);
}
int minDiffInBST(TreeNode* root) {
dfs(root);
return ans;
}
};