Update 0236.二叉树的最近公共祖先.md

This commit is contained in:
jianghongcheng
2023-05-23 21:11:37 -05:00
committed by GitHub
parent c5d1845f3f
commit daa5417db9

View File

@ -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