mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 04:54:51 +08:00
Update 0235.二叉搜索树的最近公共祖先.md
This commit is contained in:
@ -275,34 +275,57 @@ class Solution {
|
||||
|
||||
## Python
|
||||
|
||||
递归法:
|
||||
递归法(版本一)
|
||||
```python
|
||||
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 root.val > p.val and root.val > q.val:
|
||||
return self.lowestCommonAncestor(root.left, p, q)
|
||||
if root.val < p.val and root.val < q.val:
|
||||
return self.lowestCommonAncestor(root.right, p, q)
|
||||
return root
|
||||
if cur.val < p.val and cur.val < q.val: # 右
|
||||
right = self.traversal(cur.right, p, q)
|
||||
if right is not None:
|
||||
return right
|
||||
|
||||
return cur
|
||||
|
||||
def lowestCommonAncestor(self, root, p, q):
|
||||
return self.traversal(root, p, q)
|
||||
```
|
||||
|
||||
迭代法:
|
||||
迭代法(版本二)精简
|
||||
```python
|
||||
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:
|
||||
root = root.left
|
||||
elif root.val < p.val and root.val < q.val:
|
||||
root = root.right
|
||||
else:
|
||||
return root
|
||||
```
|
||||
return None
|
||||
|
||||
|
||||
```
|
||||
## Go
|
||||
|
||||
递归法:
|
||||
|
Reference in New Issue
Block a user