• [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);
            }
        }
    }
    

      

     

  • 相关阅读:
    6 docker-harbor仓库搭建
    4 dockerfile介绍及其实例应用
    1 docker 介绍和安装
    2 docker镜像
    PAT甲级1075 PAT Judge
    PAT甲级1139 First Contact【离散化】
    PAT甲级1055 The World's Richest【排序】
    PAT甲级1013-1014-1015
    洛谷P1135 奇怪的电梯【bfs】
    洛谷P1182 数列分段【二分】【贪心】
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7522840.html
Copyright © 2020-2023  润新知