Leetcode-530. Minimum Absolute Difference in BST

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。这次比赛略无语,没想到前3题都可以用暴力解。

博客链接:mcf171的博客

——————————————————————————————

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.

这个题目利用BST的特性就行,即中序遍历的输出就是一个有序的数组,我们只需要比较相邻两个节点的差,以及和当前最小的差的大小即可。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int minimum = Integer.MAX_VALUE;
    private Integer preNum = null;
    
    public int getMinimumDifference(TreeNode root) {
            helper(root);
            
            return minimum;
    }
    private void helper(TreeNode root){
        if(root == null) return;
        helper(root.right);
        if(preNum != null){
            minimum = Math.min(Math.abs(root.val - preNum), minimum);
            preNum = root.val;
        }else preNum = root.val;
        
        helper(root.left);
        
    }
}




你可能感兴趣的:(算法)