博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode | 530. Minimum Absolute Difference in BST
阅读量:3572 次
发布时间:2019-05-20

本文共 2002 字,大约阅读时间需要 6 分钟。

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

最容易想到的方法,由于是BST,直接中序遍历后即可得到排序后的list,再把排序后的list两两比较找出相差最小的值即可。

/*** Definition for a binary tree node.* public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; }* }*/public class Solution {
List
list = new ArrayList
(); public int getMinimumDifference(TreeNode root) { traverse(root); int min = Integer.MAX_VALUE; for(int i = 0; i < list.size() - 1; i++) { int absDiffer = Math.abs(list.get(i) - list.get(i+1)); min = absDiffer

由于BST本身子树间就是有序的,即可以通过递归等效实现中序遍历后两两比较的效果。代码如下:

/*** Definition for a binary tree node.* public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; }* }*/public class Solution {
private int min = Integer.MAX_VALUE; Integer prev = -1; public int getMinimumDifference(TreeNode root) { if(root == null) return min; getMinimumDifference(root.left); if(prev != -1) min = Math.min(min, Math.abs(prev - root.val)); prev = root.val; getMinimumDifference(root.right); return min; }}

而在discuss中有网友给出了如何实现非BST树时如何得出最小差值。思路就是将非BST树,利用API中的TreeSet将其转化为BST树再来进行两两比较,本质上和上面写法是一样的。

public 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, Math.abs(root.val - set.floor(root.val))); } if (set.ceiling(root.val) != null) { min = Math.min(min, Math.abs(root.val - set.ceiling(root.val))); } } set.add(root.val); getMinimumDifference(root.left); getMinimumDifference(root.right); return min; }}

转载地址:http://lijgj.baihongyu.com/

你可能感兴趣的文章
class的点点滴滴的总结
查看>>
vector 的点点滴滴的总结
查看>>
测试用例
查看>>
自动化测试学习步骤
查看>>
自动化测试需要掌握的知识
查看>>
HTTP协议
查看>>
Python小程序——冒泡排序
查看>>
cmd中输入net start mysql 提示:服务名无效或者MySQL正在启动 MySQL无法启动
查看>>
LeetCode 206反转链表 [javsScript]
查看>>
[LeetCode javaScript] 3. 无重复字符的最长子串
查看>>
[LeetCode javaScript] 6. Z字形变换
查看>>
[LeetCode javaScript]455. 分发饼干
查看>>
[LeetCode javaScript] 735. 行星碰撞
查看>>
[LeetCode javaScript] 125. 验证回文串
查看>>
[LeetCode javaScript] 226. 翻转二叉树
查看>>
[LeetCode javaScript] 520. 检测大写字母
查看>>
[LeetCode javaScript] 53.最大子序和
查看>>
[LeetCode javaScript] 101. 对称二叉树
查看>>
[LeetCode javaScript] 860. 柠檬水找零
查看>>
[LeetCode javaScript] 118. 杨辉三角
查看>>