Leetcode 530. Minimum Absolute Difference in BST | | Leetcode 530. Minimum Absolute Difference in BST 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution Version 1 1234567891011121314151617181920212223242526272829303132333435363738/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int getMinimumDifference(TreeNode* root) { vector<int> values; inOrderTranverse(root, values); int min = INT_MAX; for(int i = 1; i < values.size(); i++) { int diff = values[i] - values[i - 1]; if(min > diff) { min = diff; } } return min; } private: void inOrderTranverse(TreeNode* root, vector<int>& values) { if(!root) { return; } if(root->left) { inOrderTranverse(root->left, values); } values.push_back(root->val); if(root->right) { inOrderTranverse(root->right, values); } }}; Version 2 12345678910111213141516171819202122232425262728293031323334353637/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int getMinimumDifference(TreeNode* root) { int min = INT_MAX; int current = -1; inOrderTranverse(root, min, current); return min; } private: void inOrderTranverse(TreeNode* root, int& min, int& current) { if(!root) { return; } if(root->left) { inOrderTranverse(root->left, min, current); } if(current != -1) { if(min > root->val - current) { min = root->val - current; } } current = root->val; if(root->right) { inOrderTranverse(root->right, min, current); } }}; Reference https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏