题解 | #二叉搜索树最小差值# | C++
二叉搜索树最小差值
https://www.nowcoder.com/practice/f8ac976b49bd450887b9281f315186c7
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <climits> class Solution { void travelMidOrder(TreeNode* node, int& last_val, int& ans) { if (node == nullptr) return; travelMidOrder(node->left, last_val, ans); if (last_val != -1) { ans = std::min(ans, std::abs(node->val - last_val)); } last_val = node->val; travelMidOrder(node->right, last_val, ans); } public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ int minDifference(TreeNode* root) { int ans = INT_MAX; int last_val = -1; travelMidOrder(root, last_val, ans); return ans; } };