二叉搜索树-leetcode-530. 二叉搜索树的最小绝对差

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

给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。

输入:

   1
    \
     3
    /
   2

输出:
1

解释:
最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。

 与上一个验证搜索二叉树类似,只是将两个节点的比较换成两个节点差的绝对值

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

猜你喜欢

转载自blog.csdn.net/xiaomingds/article/details/109037234