@@ -153,23 +153,27 @@ public:
153
153
递归
154
154
```java
155
155
class Solution {
156
- TreeNode pre;// 记录上一个遍历的结点
156
+ TreeNode pre; // 记录上一个遍历的结点
157
157
int result = Integer.MAX_VALUE;
158
+
158
159
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;
162
164
}
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
+ // 左
166
170
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);
170
174
}
171
175
pre = root;
172
- //右
176
+ // 右
173
177
traversal(root.right);
174
178
}
175
179
}
@@ -182,22 +186,27 @@ class Solution {
182
186
TreeNode pre = null ;
183
187
int result = Integer . MAX_VALUE ;
184
188
185
- if (root != null )
189
+ if (root != null )
186
190
stack. add(root);
187
- while (! stack. isEmpty()){
191
+
192
+ // 中序遍历(左中右),由于栈先入后出,反序(右中左)
193
+ while (! stack. isEmpty()) {
188
194
TreeNode curr = stack. peek();
189
- if (curr != null ){
195
+ if (curr != null ) {
190
196
stack. pop();
191
- if (curr. right != null )
197
+ // 右
198
+ if (curr. right != null )
192
199
stack. add(curr. right);
200
+ // 中(先用null标记)
193
201
stack. add(curr);
194
202
stack. add(null );
195
- if (curr. left != null )
203
+ // 左
204
+ if (curr. left != null )
196
205
stack. add(curr. left);
197
- }else {
206
+ } else { // 中(遇到null再处理)
198
207
stack. pop();
199
208
TreeNode temp = stack. pop();
200
- if (pre != null )
209
+ if (pre != null )
201
210
result = Math . min(result, temp. val - pre. val);
202
211
pre = temp;
203
212
}
@@ -674,3 +683,4 @@ public class Solution
674
683
<a href =" https://programmercarl.com/other/kstar.html " target =" _blank " >
675
684
<img src =" ../pics/网站星球宣传海报.jpg " width =" 1000 " />
676
685
</a >
686
+
0 commit comments