mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
新增 0235.二叉搜索树的最近公共祖先.md Python3迭代法
This commit is contained in:
@ -268,11 +268,22 @@ class Solution:
|
||||
if root.val < p.val and root.val < q.val:
|
||||
return self.lowestCommonAncestor(root.right, p, q)
|
||||
return root
|
||||
|
||||
```
|
||||
|
||||
迭代法:
|
||||
```python
|
||||
class Solution:
|
||||
"""二叉搜索树的最近公共祖先 迭代法"""
|
||||
|
||||
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
|
||||
while True:
|
||||
if root.val > p.val and root.val > q.val:
|
||||
root = root.left
|
||||
elif root.val < p.val and root.val < q.val:
|
||||
root = root.right
|
||||
else:
|
||||
return root
|
||||
```
|
||||
|
||||
## Go
|
||||
|
||||
|
Reference in New Issue
Block a user