Problem

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.

Solution

Iterative -- using stack

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

recursive -- in-order

class Solution {
    Integer pre = null;
    int min = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        if (root == null) return min;
        getMinimumDifference(root.left);

        if (pre != null) {
            min = Math.min(min, root.val-pre);
        }
        pre = root.val;

        getMinimumDifference(root.right);

        return min;
    }
}

linspiration
161 声望53 粉丝

引用和评论

0 条评论