mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +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
|
||||
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) {
|
||||
if (root == null) return;
|
||||
getMiniDiff(root.left);
|
||||
```Java
|
||||
class Solution {
|
||||
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) {
|
||||
res = Math.min(root.val - pre.val,res);
|
||||
result = Math.min(left, root.val - pre.val);
|
||||
}
|
||||
pre = root;
|
||||
getMiniDiff(root.right);
|
||||
// 右
|
||||
int right = getMinimumDifference(root.right);
|
||||
result = Math.min(right, result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user