diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 049f70c7..7e0a12fa 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -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 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