# 【LeetCode】530. Minimum Absolute Difference in BST 解题报告（Java & Python）

900 篇文章 155 订阅
1033 篇文章 56 订阅

id： fuxuemingzhu

## 题目描述

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

Example:

Input:

1
\
3
/
2

Output:
1

Explanation:
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.

## 解题方法

### Java解法

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int minDiff = Integer.MAX_VALUE;
TreeNode prev = null;

public int getMinimumDifference(TreeNode root) {
inOrder(root);
return minDiff;
}

public void inOrder(TreeNode root){
if(root == null){
return;
}
inOrder(root.left);
if(prev !=null) minDiff= Math.min(minDiff, root.val - prev.val);
prev = root;
inOrder(root.right);
}
}


### Python解法

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.res = float("inf")
self.prev = None
self.inOrder(root)
return self.res

def inOrder(self, root):
if not root: return
self.inOrder(root.left)
if self.prev:
self.res = min(self.res, root.val - self.prev.val)
self.prev = root
self.inOrder(root.right)


## 日期

2017 年 4 月 8 日
2018 年 11 月 14 日 —— 很严重的雾霾

• 0
点赞
• 0
收藏
• 打赏
• 0
评论
09-15 218
04-30 414
07-14 1028
04-24 4076
05-24 1581
12-18 190

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。