Skip to content

Commit e6698cb

Browse files
committed
修改0530.二叉搜索树的最小绝对差.md的Java版本 进行了代码格式化并添加了统一迭代法的注释
1 parent da742fe commit e6698cb

File tree

1 file changed

+28
-18
lines changed

1 file changed

+28
-18
lines changed

problems/0530.二叉搜索树的最小绝对差.md

+28-18
Original file line numberDiff line numberDiff line change
@@ -153,23 +153,27 @@ public:
153153
递归
154154
```java
155155
class Solution {
156-
TreeNode pre;// 记录上一个遍历的结点
156+
TreeNode pre; // 记录上一个遍历的结点
157157
int result = Integer.MAX_VALUE;
158+
158159
public int getMinimumDifference(TreeNode root) {
159-
if(root==null)return 0;
160-
traversal(root);
161-
return result;
160+
if (root == null)
161+
return 0;
162+
traversal(root);
163+
return result;
162164
}
163-
public void traversal(TreeNode root){
164-
if(root==null)return;
165-
//左
165+
166+
public void traversal(TreeNode root) {
167+
if (root == null)
168+
return;
169+
// 左
166170
traversal(root.left);
167-
//中
168-
if(pre!=null){
169-
result = Math.min(result,root.val-pre.val);
171+
//
172+
if (pre != null) {
173+
result = Math.min(result, root.val - pre.val);
170174
}
171175
pre = root;
172-
//右
176+
//
173177
traversal(root.right);
174178
}
175179
}
@@ -182,22 +186,27 @@ class Solution {
182186
TreeNode pre = null;
183187
int result = Integer.MAX_VALUE;
184188

185-
if(root != null)
189+
if (root != null)
186190
stack.add(root);
187-
while(!stack.isEmpty()){
191+
192+
// 中序遍历(左中右),由于栈先入后出,反序(右中左)
193+
while (!stack.isEmpty()) {
188194
TreeNode curr = stack.peek();
189-
if(curr != null){
195+
if (curr != null) {
190196
stack.pop();
191-
if(curr.right != null)
197+
//
198+
if (curr.right != null)
192199
stack.add(curr.right);
200+
// 中(先用null标记)
193201
stack.add(curr);
194202
stack.add(null);
195-
if(curr.left != null)
203+
//
204+
if (curr.left != null)
196205
stack.add(curr.left);
197-
}else{
206+
} else { // 中(遇到null再处理)
198207
stack.pop();
199208
TreeNode temp = stack.pop();
200-
if(pre != null)
209+
if (pre != null)
201210
result = Math.min(result, temp.val - pre.val);
202211
pre = temp;
203212
}
@@ -674,3 +683,4 @@ public class Solution
674683
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
675684
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
676685
</a>
686+

0 commit comments

Comments
 (0)