From c41ce18dbbac14336d49f006c3d864f0b3a232f9 Mon Sep 17 00:00:00 2001 From: Wen Date: Fri, 17 Sep 2021 20:21:56 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=200236.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96?= =?UTF-8?q?=E5=85=88.md=20Python3=E8=A7=A3=E6=B3=95=20=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E8=AF=AD=E6=B3=95=E9=94=99=E8=AF=AF=EF=BC=8C=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?Python=E8=AF=AD=E6=B3=95=E9=A3=8E=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0236.二叉树的最近公共祖先.md | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 59345a24..46dcb545 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -264,16 +264,21 @@ class Solution { ## Python ```python -//递归 class Solution: + """二叉树的最近公共祖先 递归法""" + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': - if not root or root == p or root == q: return root //找到了节点p或者q,或者遇到空节点 - left = self.lowestCommonAncestor(root.left,p,q) //左 - right = self.lowestCommonAncestor(root.right,p,q) //右 - if left and right: return root //中: left和right不为空,root就是最近公共节点 - elif left and not right: return left //目标节点是通过left返回的 - elif not left and right: return right //目标节点是通过right返回的 - else: return None //没找到 + if not root or root == p or root == q: + return root + + left = self.lowestCommonAncestor(root.left, p, q) + right = self.lowestCommonAncestor(root.right, p, q) + + if left and right: + return root + if left: + return left + return right ``` ## Go