平衡二叉树的最小差值 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).

解决:

① 通过中序遍历可以得到一个有序数列,然后将当前节点值和之前节点值求绝对差并更新结果min。需要注意的就是在处理第一个节点值时,由于其没有前节点,所以不能求绝对差。这里我们用变量pre来表示前节点值,这里由于题目中说明了所以节点值不为负数,所以我们给pre初始化-1,这样我们就知道pre是否存在。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution { //17ms
    int minVal = Integer.MAX_VALUE;
    int pre = -1;
    public int getMinimumDifference(TreeNode root) {
        inorder(root);
        return minVal;
    }
    public void inorder(TreeNode root){
        if(root == null) return;
        inorder(root.left);
        if(pre != -1) minVal = Math.min(minVal,root.val - pre);
        pre = root.val;
        inorder(root.right);
    }
}

② 进化版

public class Solution { //14ms
    int min = Integer.MAX_VALUE;//因为使用了递归方法,所以必须声明为全局变量,否则结果错误
    Integer prev = null;
    public int getMinimumDifference(TreeNode root) {
        if (root == null) return min;
        getMinimumDifference(root.left);
        if (prev != null) {
            min = Math.min(min, root.val - prev);
        }
        prev = root.val;
        getMinimumDifference(root.right);
        return min;
    }
}

③ 使用非递归方法实现。

public class Solution { //19ms
    public int getMinimumDifference(TreeNode root) {
        int minVal = Integer.MAX_VALUE;
        int pre = -1;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(cur != null || ! stack.isEmpty()){
            while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            if(pre != -1) minVal = Math.min(minVal,cur.val - pre);
            pre = cur.val;
            cur = cur.right;
        }
        return minVal;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1518785

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值