parent
f46c111d9e
commit
c41ce18dbb
|
|
@ -264,16 +264,21 @@ class Solution {
|
||||||
## Python
|
## Python
|
||||||
|
|
||||||
```python
|
```python
|
||||||
//递归
|
|
||||||
class Solution:
|
class Solution:
|
||||||
|
"""二叉树的最近公共祖先 递归法"""
|
||||||
|
|
||||||
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
|
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
|
||||||
if not root or root == p or root == q: return root //找到了节点p或者q,或者遇到空节点
|
if not root or root == p or root == q:
|
||||||
left = self.lowestCommonAncestor(root.left,p,q) //左
|
return root
|
||||||
right = self.lowestCommonAncestor(root.right,p,q) //右
|
|
||||||
if left and right: return root //中: left和right不为空,root就是最近公共节点
|
left = self.lowestCommonAncestor(root.left, p, q)
|
||||||
elif left and not right: return left //目标节点是通过left返回的
|
right = self.lowestCommonAncestor(root.right, p, q)
|
||||||
elif not left and right: return right //目标节点是通过right返回的
|
|
||||||
else: return None //没找到
|
if left and right:
|
||||||
|
return root
|
||||||
|
if left:
|
||||||
|
return left
|
||||||
|
return right
|
||||||
```
|
```
|
||||||
|
|
||||||
## Go
|
## Go
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue