码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-01-13 21:01:44      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:and   href   exp   not   void   class   bin   rip   wiki   

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

标签:and   href   exp   not   void   class   bin   rip   wiki   

原文地址:https://www.cnblogs.com/chenhan05/p/8280289.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!