530. Minimum Absolute Difference in BST

网友投稿 620 2022-09-04

530. Minimum Absolute Difference in BST

530. Minimum Absolute Difference in BST

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.

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { TreeSet set = new TreeSet<>(); int min = Integer.MAX_VALUE; public int getMinimumDifference(TreeNode root) { if (root == null) return min; if (!set.isEmpty()) { if (set.floor(root.val) != null) { min = Math.min(min, root.val - set.floor(root.val)); } if (set.ceiling(root.val) != null) { min = Math.min(min, set.ceiling(root.val) - root.val); } } set.add(root.val); getMinimumDifference(root.left); getMinimumDifference(root.right); return min; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:MySQL实战:order by 语句怎么优化?
下一篇:学会这 2 点,轻松看懂 MySQL 慢查询日志(学会这套组合拳街头无敌)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~