Minimum Absolute Difference in BST

来源:互联网 发布:做淘宝新手怎么找货源 编辑:程序博客网 时间:2024/06/05 10:02

题目:

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

Example:

Input:   1    \     3    /   2Output:1Explanation: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.



tips:传统的遍历树,取值存入集合类,唯一要看清题目,要求的是所有数据之间的比较,不是父子节点的比较


/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {     public int getMinimumDifference(TreeNode root) {            ArrayList<Integer> list=new ArrayList<Integer>();            getData(root,list);            int min=Integer.MAX_VALUE;            Collections.sort(list, new Comparator<Integer>() {                @Override                public int compare(Integer o1, Integer o2) {                    return o2-o1;                }            });   //那个时候脑子傻掉了,这里直接Collections.sort(list),以后比较的时候连绝对值都不要加,搞麻烦了            for(int i=1;i < list.size(); i++){                min=Math.min(Math.abs(list.get(i)-list.get(i-1)),min);            }            return min;        }        public void getData(TreeNode root,ArrayList<Integer> list)        {            if(root==null)                return;            //中序遍历            getData(root.left,list);            list.add(root.val);            getData(root.right,list);        }}


0 0
原创粉丝点击