Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input: 1 3 / 2 Output: 1 Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note: There are at least two nodes in this BST.
class Solution { public: int getMinimumDifference(TreeNode* root) { int res = INT_MAX, pre = -1; inorder(root, pre, res); return res; } void inorder(TreeNode* root, int& pre, int& res) { if (!root) return; inorder(root->left, pre, res); if (pre != -1) res = min(res, root->val - pre); pre = root->val; inorder(root->right, pre, res); } };
原文地址:https://www.cnblogs.com/chenhan05/p/8280289.html
时间: 2024-11-02 00:01:44