[leetcode]Binary Search Tree-530. Minimum Absolute Difference in BST

Posted chenhan05

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]Binary Search Tree-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 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);
    }
};

 

以上是关于[leetcode]Binary Search Tree-530. Minimum Absolute Difference in BST的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode算法题-Lowest Common Ancestor of a Binary Search Tree

[Leetcode] Binary search tree --Binary Search Tree Iterator

LeetCode Closest Binary Search Tree Value

LeetCode 704. Binary Search

[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree

[Leetcode] Recover Binary Search Tree