Merge pull request #106 from Joshua-Lu/patch-23

更新 0530.二叉搜索树的最小绝对差 Java版本
This commit is contained in:
Carl Sun
2021-05-14 10:38:03 +08:00
committed by GitHub

View File

@ -151,23 +151,27 @@ public:
Java Java
```java
class Solution {
private TreeNode pre = null;
private int res = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
getMiniDiff(root);
return res;
}
private void getMiniDiff (TreeNode root) { ```Java
if (root == null) return; class Solution {
getMiniDiff(root.left); TreeNode pre;// 记录上一个遍历的结点
int result = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if (root == null) {
return result;
}
// 左
int left = getMinimumDifference(root.left);
// 中
if (pre != null) { if (pre != null) {
res = Math.min(root.val - pre.val,res); result = Math.min(left, root.val - pre.val);
} }
pre = root; pre = root;
getMiniDiff(root.right); // 右
int right = getMinimumDifference(root.right);
result = Math.min(right, result);
return result;
} }
} }
``` ```