mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0236.二叉树的最近公共祖先.md
0236 java简洁迭代解法
This commit is contained in:
@ -247,7 +247,7 @@ public:
|
||||
|
||||
|
||||
### Java
|
||||
|
||||
递归
|
||||
```Java
|
||||
class Solution {
|
||||
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
|
||||
|
Reference in New Issue
Block a user