Skip to content

Commit fb03de4

Browse files
authored
Update 0236.二叉树的最近公共祖先.md
0236 java简洁迭代解法
1 parent 3dd5b33 commit fb03de4

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

problems/0236.二叉树的最近公共祖先.md

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ public:
247247
248248
249249
### Java
250-
250+
递归
251251
```Java
252252
class Solution {
253253
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
@@ -271,6 +271,47 @@ class Solution {
271271
}
272272
}
273273
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+
274315
```
275316

276317
### Python

0 commit comments

Comments
 (0)