1. 程式人生 > >[leetcode]Binary Search Tree-530. Minimum Absolute Difference in BST

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

public ren etc bsp edi this des search turn

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