mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 04:54:51 +08:00
Update 0236.二叉树的最近公共祖先.md
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user