补第十二周Leetcode算法博客
530. Minimum Absolute Difference in BST
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 mini = INT_MAX;
int pre = -1;
int getMinimumDifference(TreeNode* root) {
if (root -> left != NULL)
getMinimumDifference(root -> left);
if (pre >= 0) {
mini = min(mini, root->val - pre);
}
pre = root -> val;
if (root -> right != NULL)
getMinimumDifference(root -> right);
return mini;
}
};