From 43f30b23ab2928f277793bfede1df028b4dd4cfb Mon Sep 17 00:00:00 2001 From: Wen Date: Sat, 18 Sep 2021 22:17:47 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=200235.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC?= =?UTF-8?q?=E5=85=B1=E7=A5=96=E5=85=88.md=20Python3=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0235.二叉搜索树的最近公共祖先.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index 929e6eb2..7fad5af0 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -260,13 +260,15 @@ class Solution { 递归法: ```python class Solution: + """二叉搜索树的最近公共祖先 递归法""" + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': - if not root: return root //中 - if root.val >p.val and root.val > q.val: - return self.lowestCommonAncestor(root.left,p,q) //左 - elif root.val < p.val and root.val < q.val: - return self.lowestCommonAncestor(root.right,p,q) //右 - else: return root + if root.val > p.val and root.val > q.val: + return self.lowestCommonAncestor(root.left, p, q) + if root.val < p.val and root.val < q.val: + return self.lowestCommonAncestor(root.right, p, q) + return root + ``` 迭代法: