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 + ``` 迭代法: