Skip to content

Commit 5155c81

Browse files
authored
添加 0236. 二叉树的最近公共祖先 python版本
added python version of code
1 parent c87d709 commit 5155c81

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

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

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -263,8 +263,24 @@ class Solution {
263263
```
264264

265265
Python:
266-
267-
266+
```python
267+
# Definition for a binary tree node.
268+
# class TreeNode:
269+
# def __init__(self, x):
270+
# self.val = x
271+
# self.left = None
272+
# self.right = None
273+
//递归
274+
class Solution:
275+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
276+
if not root or root == p or root == q: return root //找到了节点p或者q,或者遇到空节点
277+
left = self.lowestCommonAncestor(root.left,p,q) //
278+
right = self.lowestCommonAncestor(root.right,p,q) //
279+
if left and right: return root //中: left和right不为空,root就是最近公共节点
280+
elif left and not right: return left //目标节点是通过left返回的
281+
elif not left and right: return right //目标节点是通过right返回的
282+
else: return None //没找到
283+
```
268284
Go:
269285
```Go
270286
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {

0 commit comments

Comments
 (0)