[LeetCode] 530. Minimum Absolute Difference in BST Java

题目:

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.

题意及分析:给出一颗二叉搜索树(节点为非负),要求求出任意两个点之间差值绝对值的最小值。题目简单,直接中序遍历二叉树,得到一个升序排列的list,然后计算每两个数差的绝对值,每次和当前最小值进行比较,若小于当前最小值,替换掉即可。

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int getMinimumDifference(TreeNode root) {        //中根序遍历,然后比较每相邻的两个数
        List<Integer> list = new ArrayList<>();
        search(list,root);
        int min = Integer.MAX_VALUE;
        for(int i=0;i<list.size()-1;i++){
            int temp = Math.abs(list.get(i+1)-list.get(i));
            if(temp<min)
                min = temp;
        }
        return min;
    }

    private void search( List<Integer> list,TreeNode node){
        if(node!=null){
            search(list,node.left);
            list.add(node.val);
            search(list,node.right);
        }
    }
}

  

 

原文地址:https://www.cnblogs.com/271934Liao/p/7522840.html