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

This commit is contained in:
jianghongcheng
2023-05-23 21:16:37 -05:00
committed by GitHub
parent daa5417db9
commit e7b7aa8e4a

View File

@ -275,34 +275,57 @@ class Solution {
## Python ## Python
递归法 递归法(版本一)
```python ```python
class Solution: class Solution:
"""二叉搜索树的最近公共祖先 递归法""" def traversal(self, cur, p, q):
if cur is None:
return cur
# 中
if cur.val > p.val and cur.val > q.val: # 左
left = self.traversal(cur.left, p, q)
if left is not None:
return left
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if cur.val < p.val and cur.val < q.val: # 右
if root.val > p.val and root.val > q.val: right = self.traversal(cur.right, p, q)
return self.lowestCommonAncestor(root.left, p, q) if right is not None:
if root.val < p.val and root.val < q.val: return right
return self.lowestCommonAncestor(root.right, p, q)
return root return cur
def lowestCommonAncestor(self, root, p, q):
return self.traversal(root, p, q)
``` ```
迭代法 迭代法(版本二)精简
```python ```python
class Solution: class Solution:
"""二叉搜索树的最近公共祖先 迭代法""" def lowestCommonAncestor(self, root, p, q):
if root.val > p.val and root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
elif root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
else:
return root
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': ```
while True:
迭代法
```python
class Solution:
def lowestCommonAncestor(self, root, p, q):
while root:
if root.val > p.val and root.val > q.val: if root.val > p.val and root.val > q.val:
root = root.left root = root.left
elif root.val < p.val and root.val < q.val: elif root.val < p.val and root.val < q.val:
root = root.right root = root.right
else: else:
return root return root
``` return None
```
## Go ## Go
递归法: 递归法: