File tree Expand file tree Collapse file tree 1 file changed +42
-1
lines changed Expand file tree Collapse file tree 1 file changed +42
-1
lines changed Original file line number Diff line number Diff line change @@ -247,7 +247,7 @@ public:
247
247
248
248
249
249
### Java
250
-
250
+ 递归
251
251
```Java
252
252
class Solution {
253
253
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
@@ -271,6 +271,47 @@ class Solution {
271
271
}
272
272
}
273
273
274
+ ```
275
+ 迭代
276
+ ``` Java
277
+ class Solution {
278
+ public TreeNode lowestCommonAncestor (TreeNode root , TreeNode p , TreeNode q ) {
279
+ int max = Integer . MAX_VALUE ;
280
+ Stack<TreeNode > st = new Stack<> ();
281
+ TreeNode cur = root, pre = null ;
282
+ while (cur != null || ! st. isEmpty()) {
283
+ while (cur != null ) {
284
+ st. push(cur);
285
+ cur = cur. left;
286
+ }
287
+ cur = st. pop();
288
+ if (cur. right == null || cur. right == pre) {
289
+ // p/q是 中/左 或者 中/右 , 返回中
290
+ if (cur == p || cur == q) {
291
+ if ((cur. left != null && cur. left. val == max) || (cur. right != null && cur. right. val == max)) {
292
+ return cur;
293
+ }
294
+ cur. val = max;
295
+ }
296
+ // p/q是 左/右 , 返回中
297
+ if (cur. left != null && cur. left. val == max && cur. right != null && cur. right. val == max) {
298
+ return cur;
299
+ }
300
+ // MAX_VALUE 往上传递
301
+ if ((cur. left != null && cur. left. val == max) || (cur. right != null && cur. right. val == max)) {
302
+ cur. val = max;
303
+ }
304
+ pre = cur;
305
+ cur = null ;
306
+ } else {
307
+ st. push(cur);
308
+ cur = cur. right;
309
+ }
310
+ }
311
+ return null ;
312
+ }
313
+ }
314
+
274
315
```
275
316
276
317
### Python
You can’t perform that action at this time.
0 commit comments