题解 | #牛群最小体重差#
牛群最小体重差
https://www.nowcoder.com/practice/e96bd1aad52a468d9bff3271783349c1
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <climits> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ int pre = 0; int minDiff = INT_MAX; // 使用中序遍历的方式,求解最小差值 void inordered(TreeNode* root) { if (root == nullptr) return; inordered(root->left); if (pre != 0 && root->val - pre < minDiff) { minDiff = root->val - pre; } pre = root->val; inordered(root->right); } int getMinimumDifference(TreeNode* root) { // write code here inordered(root); return minDiff; } };