[leetcode] 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.

这道题是找二叉搜索树中任意两节点之间的最小绝对差,题目难度为Easy。

我们知道按中序遍历BST得到的节点值是递增的,题目限定BST中所有节点值非负,因此只需要比较中序遍历时所有相邻节点的绝对差即可得到最小绝对差。这样题目就变成了中序遍历二叉树的问题,大家可以顺便看下第94题(传送门)和第145题(传送门)。

遍历二叉树可以通过递归和非递归两种方法,递归的方法比较简单,不再详细说明,具体代码:

class Solution {
    void inorder(TreeNode* p, int& minDiff, int& pre) {
        if(p->left) inorder(p->left, minDiff, pre);
        if(pre != -1) minDiff = min(minDiff, p->val - pre);
        pre = p->val;
        if(p->right) inorder(p->right, minDiff, pre);
    }
public:
    int getMinimumDifference(TreeNode* root) {
        int minDiff = INT_MAX, pre = -1;
        inorder(root, minDiff, pre);
        return minDiff;
    }
};

非递归的方法需要借助栈来记录遍历路径上的节点,具体说明请查看第145题(传送门的详细说明, 具体代码:

class Solution {
public:
    int getMinimumDifference(TreeNode* root) {
        int minDiff = INT_MAX, pre = -1;
        stack<TreeNode*> stk;
        TreeNode* p = root;
        
        while(p || !stk.empty()) {
            while(p) {
                stk.push(p);
                p = p->left;
            }
            p = stk.top();
            stk.pop();
            if(pre != -1) minDiff = min(minDiff, p->val - pre);
            pre = p->val;
            p = p->right;
        }
        
        return minDiff;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值