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

Commit 08199d5

Browse files
committed
新增 0235.二叉搜索树的最近公共祖先.md Python3迭代法
1 parent 43f30b2 commit 08199d5

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

problems/0235.二叉搜索树的最近公共祖先.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,11 +268,22 @@ class Solution:
268268
if root.val < p.val and root.val < q.val:
269269
return self.lowestCommonAncestor(root.right, p, q)
270270
return root
271-
272271
```
273272

274273
迭代法:
274+
```python
275+
class Solution:
276+
"""二叉搜索树的最近公共祖先 迭代法"""
275277

278+
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
279+
while True:
280+
if root.val > p.val and root.val > q.val:
281+
root = root.left
282+
elif root.val < p.val and root.val < q.val:
283+
root = root.right
284+
else:
285+
return root
286+
```
276287

277288
## Go
278289

0 commit comments

Comments
 (0)