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

0236 java简洁迭代解法
This commit is contained in:
carlvine500
2024-04-02 17:46:11 +08:00
committed by GitHub
parent 3dd5b33cec
commit fb03de4c4e

View File

@ -247,7 +247,7 @@ public:
### Java ### Java
递归
```Java ```Java
class Solution { class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
@ -271,6 +271,47 @@ class Solution {
} }
} }
```
迭代
```Java
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
int max = Integer.MAX_VALUE;
Stack<TreeNode> st = new Stack<>();
TreeNode cur = root, pre = null;
while (cur != null || !st.isEmpty()) {
while (cur != null) {
st.push(cur);
cur = cur.left;
}
cur = st.pop();
if (cur.right == null || cur.right == pre) {
// p/q是 中/左 或者 中/右 , 返回中
if (cur == p || cur == q) {
if ((cur.left != null && cur.left.val == max) || (cur.right != null && cur.right.val == max)) {
return cur;
}
cur.val = max;
}
// p/q是 左/右 , 返回中
if (cur.left != null && cur.left.val == max && cur.right != null && cur.right.val == max) {
return cur;
}
// MAX_VALUE 往上传递
if ((cur.left != null && cur.left.val == max) || (cur.right != null && cur.right.val == max)) {
cur.val = max;
}
pre = cur;
cur = null;
} else {
st.push(cur);
cur = cur.right;
}
}
return null;
}
}
``` ```
### Python ### Python