LeetCode 530. Minimum Absolute Difference in BST
Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
Example 1:
Input: root = [4,2,6,1,3]
Output: 1
method: 中序遍历
中序遍历,相当于遍历一个有序数组,求出两两之前的差值,更新其最小值
TreeNode *pre = nullptr;
int result = INT_MAX;
void traversal(TreeNode* root) {
if (!root) return;
traversal(root->left);
if (pre) {
result = min(result, root->val - pre->val); // 更新最小值
}
pre = root;
traversal(root->right);
}
int getMinimumDifference(TreeNode* root) {
traversal(root);
return result;
}