LeetCode 783. 二叉搜索树节点最小距离
原题链接
简单
作者:
飞呀
,
2021-05-07 11:31:17
,
所有人可见
,
阅读 201
/**
* 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;
vector<int> nums;
void preOrder(TreeNode* root){
if(root == nullptr) return;
nums.push_back(root->val);
preOrder(root->left);
preOrder(root->right);
}
int minDiffInBST(TreeNode* root) {
preOrder(root);
int n = nums.size();
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
ans = min(ans, abs(nums[i] - nums[j]));
}
}
return ans;
}
};