玩命加载中 . . .

530-二叉搜索树的最小绝对差


LeetCode 530. Minimum Absolute Difference in BST

LeetCode-530

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;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录