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
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Leetcode-530. Minimum Absolute Difference in BST
- LeetCode: 503.Minimum Absolute Difference in BST
- 【Leetcode】530. Minimum Absolute Difference in BST
- Leetcode 530. Minimum Absolute Difference in BST
- 530. Minimum Absolute Difference in BST
- 530. Minimum Absolute Difference in BST
- Leetcode #530 Minimum Absolute Difference in BST
- [leetcode] 530. Minimum Absolute Difference in BST
- 530. Minimum Absolute Difference in BST
- LeetCode-530. Minimum Absolute Difference in BST
- 第4节 使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用【Linux内核分析】
- n阶矩阵一般乘法-《算法导论》学习笔记五
- 多线程
- smart基本命令
- intellij idea 导出可发布的maven web 项目
- Minimum Absolute Difference in BST
- OpenCv-python之基础图像知识
- Spring Session + Redis实现分布式Session共享
- TensorFlow基础知识点(六)/矩阵基本操作
- CSS3实现优酷轮播图
- ThreadPoolExecutor的使用
- 屏幕相关的辅助类
- Maven常用命令整理
- 104-记录锁(概念)