【两次过】Lintcode 1188. BST的最小绝对差

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/83616547

给定具有非负值的二叉搜索树,找到任意两个节点的值之间的最小绝对差值.

样例

输入
   1
    \
     3
    /
   2

输出:
1

说明:
最小绝对差值为1,即2和1(或2和3之间)之差。

注意事项

此BST中至少有两个节点。


解题思路1:

我们知道按中序遍历BST得到的节点值是递增的,题目限定BST中所有节点值非负,因此只需要比较中序遍历时所有相邻节点的绝对差即可得到最小绝对差。这样题目就变成了中序遍历二叉树的问题。

利用二叉搜索树的性质可知,所求值可能出现在以下两处:

  • 根节点左/右子树相邻两个节点之差
  • 根节点左子树最大值和根节点右子树最小值
    那么利用递归,在遍历时记录上一个遍历的节点(pre),然后用当前节点减去pre即可获得相邻节点之差。而且遍历完左子树最后一个节点,进入根节点右子树前,pre刚好为左子树最大值,而此时根节点为右子树最小值,因此可以检测条件2
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    int min = Integer.MAX_VALUE;
    int pre = -1;
    /**
     * @param root: the root
     * @return: the minimum absolute difference between values of any two nodes
     */
    public int getMinimumDifference(TreeNode root) {
        // Write your code here
        if (root == null)
            return min;
        
        getMinimumDifference(root.left);
        
        if (pre != -1) 
            min = Math.min(min, root.val - pre);
        
        pre = root.val;
        
        getMinimumDifference(root.right);
        
        return min;
    }
    
    

}

解题思路2:

非递归。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the root
     * @return: the minimum absolute difference between values of any two nodes
     */
    public int getMinimumDifference(TreeNode root) {
        // Write your code here
        Stack<TreeNode> stack = new Stack<>();
        int pre = -1;
        int min = Integer.MAX_VALUE;
        
        while(root!=null || !stack.isEmpty()){
            while(root != null){
                stack.push(root);
                root = root.left;
            }
            
            root = stack.pop();
            if(pre != -1)
                min = Math.min(min, root.val - pre);
            
            pre = root.val;
            root = root.right;
        }
        
        return min;
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/83616547