[LeetCode] 530. Minimum Absolute Difference in BST Java

Posted BrookLearnData

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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);
        }
    }
}

  

 

以上是关于[LeetCode] 530. Minimum Absolute Difference in BST Java的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 530. Minimum Absolute Difference in BST

530. Minimum Absolute Difference in BST(LeetCode)

[LeetCode] 530. Minimum Absolute Difference in BST Java

[leetcode]Binary Search Tree-530. Minimum Absolute Difference in BST

LeetCode 530. Minimum Absolute Difference in BST(在二叉查找树中查找两个节点之差的最小绝对值)

530. Minimum Absolute Difference in BST