Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c41ce18

Browse files
committed
修复 0236.二叉树的最近公共祖先.md Python3解法
修正语法错误,修复Python语法风格
1 parent f46c111 commit c41ce18

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

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

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -264,16 +264,21 @@ class Solution {
264264
## Python
265265

266266
```python
267-
//递归
268267
class Solution:
268+
"""二叉树的最近公共祖先 递归法"""
269+
269270
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
270-
if not root or root == p or root == q: return root //找到了节点p或者q,或者遇到空节点
271-
left = self.lowestCommonAncestor(root.left,p,q) //
272-
right = self.lowestCommonAncestor(root.right,p,q) //
273-
if left and right: return root //中: left和right不为空,root就是最近公共节点
274-
elif left and not right: return left //目标节点是通过left返回的
275-
elif not left and right: return right //目标节点是通过right返回的
276-
else: return None //没找到
271+
if not root or root == p or root == q:
272+
return root
273+
274+
left = self.lowestCommonAncestor(root.left, p, q)
275+
right = self.lowestCommonAncestor(root.right, p, q)
276+
277+
if left and right:
278+
return root
279+
if left:
280+
return left
281+
return right
277282
```
278283

279284
## Go

0 commit comments

Comments
 (0)