530. Minimum Absolute Difference in BST

https://leetcode.com/problems/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.
  • This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

算法思路:

inOrder

class Solution {
public:
    int getMinimumDifference(TreeNode* root) {
        int prev = -1;
        int diff = INT_MAX;
        inorder(root, prev, diff);
        return diff;
    }
private:
    void inorder(TreeNode* node, int& prev, int& diff) {
        if (node == nullptr) return;
        inorder(node->left, prev, diff);
        if (prev >= 0) diff = min(diff, node->val - prev);
        prev = node->val;
        inorder(node->right, prev, diff);
    }
};

 

 

你可能感兴趣的:(leetcode)