mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 13:00:22 +08:00
Update 0236.二叉树的最近公共祖先.md
This commit is contained in:
@ -274,25 +274,44 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Python
|
## Python
|
||||||
|
递归法(版本一)
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
"""二叉树的最近公共祖先 递归法"""
|
def lowestCommonAncestor(self, root, p, q):
|
||||||
|
if root == q or root == p or root is None:
|
||||||
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
|
|
||||||
if not root or root == p or root == q:
|
|
||||||
return root
|
return root
|
||||||
|
|
||||||
left = self.lowestCommonAncestor(root.left, p, q)
|
left = self.lowestCommonAncestor(root.left, p, q)
|
||||||
right = self.lowestCommonAncestor(root.right, p, q)
|
right = self.lowestCommonAncestor(root.right, p, q)
|
||||||
|
|
||||||
if left and right:
|
if left is not None and right is not None:
|
||||||
return root
|
return root
|
||||||
if left:
|
|
||||||
return left
|
|
||||||
return right
|
|
||||||
```
|
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
```Go
|
```Go
|
||||||
|
Reference in New Issue
Block a user