领扣LintCode算法问题答案-1188. BST的最小绝对差
发布日期:2021-06-30 17:10:15
浏览次数:2
分类:技术文章
本文共 1468 字,大约阅读时间需要 4 分钟。
领扣LintCode算法问题答案-1188. BST的最小绝对差
目录
1188. BST的最小绝对差
描述
给定具有非负值的二叉搜索树,找到任意两个节点的值之间的最小绝对差值.
- 此BST中至少有两个节点。
样例 1:
输入 1 \ 3 / 2输出:1说明:最小绝对差值为1,即2和1(或2和3之间)之差。
题解
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */public class Solution { /** * @param root: the root * @return: the minimum absolute difference between values of any two nodes */ public int getMinimumDifference(TreeNode root) { // Write your code here ListallValue = new ArrayList<>(); Queue q = new LinkedList<>(); q.offer(root); while (!q.isEmpty()) { TreeNode node = q.poll(); allValue.add(node.val); if (node.left != null) { q.offer(node.left); } if (node.right != null) { q.offer(node.right); } } Collections.sort(allValue); int minDiff = Integer.MAX_VALUE; for (int i = 1; i < allValue.size(); i++) { int diff = allValue.get(i) - allValue.get(i - 1); if (diff < minDiff) { minDiff = diff; } } return minDiff; }}
鸣谢
非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。
欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。
转载地址:https://le-yi.blog.csdn.net/article/details/108892935 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2024年04月30日 17时47分11秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
[off by null + tcache dup]lctf_easy_heap
2019-04-30
[pie+libc]national2021_pwny
2019-04-30
task_struct 结构分析
2019-04-30
Linux创建进程的源码分析
2019-04-30
ubunut16.04的pip3出现问题,重新安装pip3
2019-04-30
how2heap-double free
2019-04-30
how2heap-fastbin_dup_consolidate
2019-04-30
orw_shellcode_模板
2019-04-30
[fmt+shellcode]string
2019-04-30
fmt在bss段(neepusec_easy_format)
2019-04-30
[double free] 9447 CTF : Search Engine
2019-04-30
python 函数式编程
2019-04-30
python编码
2019-04-30
scala maven plugin
2019-04-30
flink 1-个人理解
2019-04-30
redis cli
2019-04-30
redis api
2019-04-30
flink physical partition
2019-04-30
java 解析json
2019-04-30