zoukankan      html  css  js  c++  java
  • [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);
            }
        }
    }
    

      

     

  • 相关阅读:
    随机数、无重复、冒泡排序
    今天是星期几
    Button
    2012/8/5为应用指定多个配置文件
    2012/8/4解决JSP显示中文乱码
    2012/8/4 struts2学习笔记
    2012/8/4Action中result的各种转发类型
    2012/8/4为Action属性注入值
    2012/8/3SVN小入门
    2012/8/3 Extjs使用TabPanel时需要注意的问题
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7522840.html
Copyright © 2011-2022 走看看