mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #106 from Joshua-Lu/patch-23
更新 0530.二叉搜索树的最小绝对差 Java版本
This commit is contained in:
@ -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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
Reference in New Issue
Block a user