diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 33201def..0ebd5566 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -274,25 +274,44 @@ 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: + def lowestCommonAncestor(self, root, p, q): + if root == q or root == p or root is None: 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 -``` + if left is not None and right is not None: + return root + + if left is None and right is not None: + return right + elif left is not None and right is None: + return left + else: + return None +``` +递归法(版本二)精简 +```python +class Solution: + def lowestCommonAncestor(self, root, p, q): + if root == q or root == p or root is None: + return root + + left = self.lowestCommonAncestor(root.left, p, q) + right = self.lowestCommonAncestor(root.right, p, q) + + if left is not None and right is not None: + return root + + if left is None: + return right + return left + +``` ## Go ```Go