From fb03de4c4ed82d239102718565c4734e01a211ac Mon Sep 17 00:00:00 2001 From: carlvine500 Date: Tue, 2 Apr 2024 17:46:11 +0800 Subject: [PATCH] =?UTF-8?q?Update=200236.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96=E5=85=88?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0236 java简洁迭代解法 --- .../0236.二叉树的最近公共祖先.md | 43 ++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) 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