mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
修复 0235.二叉搜索树的最近公共祖先.md Python3解法
This commit is contained in:
@ -260,13 +260,15 @@ class Solution {
|
|||||||
递归法:
|
递归法:
|
||||||
```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: return root //中
|
if root.val > p.val and root.val > q.val:
|
||||||
if root.val >p.val and root.val > q.val:
|
return self.lowestCommonAncestor(root.left, p, q)
|
||||||
return self.lowestCommonAncestor(root.left,p,q) //左
|
if root.val < p.val and root.val < q.val:
|
||||||
elif root.val < p.val and root.val < q.val:
|
return self.lowestCommonAncestor(root.right, p, q)
|
||||||
return self.lowestCommonAncestor(root.right,p,q) //右
|
return root
|
||||||
else: return root
|
|
||||||
```
|
```
|
||||||
|
|
||||||
迭代法:
|
迭代法:
|
||||||
|
Reference in New Issue
Block a user