LeetCode 783. 二叉搜索树节点最小距离
原题链接
简单
作者:
回归线
,
2021-04-13 17:19:59
,
所有人可见
,
阅读 240
/**
* 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 {
private:
int ans = INT_MAX;
void dfs(TreeNode* root, int& pre) {
if (!root) {
return;
}
dfs(root->left, pre);
if (pre >= 0) {
ans = min(ans, root->val - pre);
}
pre = root -> val;
dfs(root->right, pre);
}
public:
int minDiffInBST(TreeNode* root) {
int pre = -1;
dfs(root, pre);
return ans;
}
};