leetcode530. 二叉搜索树的最小绝对差

1.题目描述:

给你一个二叉搜索树的根节点root,返回树中任意两不同节点值之间的最小差值。差值为绝对值。

leetcode530. 二叉搜索树的最小绝对差_第1张图片

 2.借助集合(任意二叉树成立):

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private List list = new ArrayList<>();
    public int getMinimumDifference(TreeNode root) {
        inOrder(root);
        return getMini(list);
    }

    public void inOrder(TreeNode root) {
        if (root == null) return;
        inOrder(root.left);
        list.add(root.val);
        inOrder(root.right);
    }

    public int getMini(List list) {
        int min = Integer.MAX_VALUE;
        int size = list.size();
        for (int i = 0; i < size; i++) {
            for (int j = i + 1; j < size;j++) {
                min = Math.min(Math.abs(list.get(i) - list.get(j)), min);
            }
        }
        return min;
    }
}

3.中序遍历(迭代):

考虑到题目条件是二叉搜索树,中序遍历之后为升序结构,升序结构找最小绝对差就是相邻元素的最小绝对值差,也就可以在遍历中通过借助前驱节点pre来维护最小差值,代码写法和leetcode98. 验证二叉搜索树中的后面两种写法类似。

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

4.中序遍历(递归):

class Solution {
    private int min = Integer.MAX_VALUE;
    private TreeNode pre = null;
    public int getMinimumDifference(TreeNode root) {
        if (root == null) return min;
        getMinimumDifference(root.left);
        if (pre != null) min = Math.min(root.val - pre.val, min);
        pre = root;
        getMinimumDifference(root.right);
        return min;         
    }
}

你可能感兴趣的:(树,数据结构,算法,leetcode,java,树结构)