mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
Merge pull request #763 from RyouMon/master
修复 0236.二叉树的最近公共祖先.md/0235.二叉搜索树的最近公共祖先.md Python3解法
This commit is contained in:
@ -268,17 +268,30 @@ class Solution {
|
||||
递归法:
|
||||
```python
|
||||
class Solution:
|
||||
"""二叉搜索树的最近公共祖先 递归法"""
|
||||
|
||||
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:
|
||||
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
|
||||
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
|
||||
```
|
||||
|
||||
迭代法:
|
||||
```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
|
||||
|
||||
|
@ -264,16 +264,21 @@ class Solution {
|
||||
## Python
|
||||
|
||||
```python
|
||||
//递归
|
||||
class Solution:
|
||||
"""二叉树的最近公共祖先 递归法"""
|
||||
|
||||
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
|
||||
if not root or root == p or root == q: return root //找到了节点p或者q,或者遇到空节点
|
||||
left = self.lowestCommonAncestor(root.left,p,q) //左
|
||||
right = self.lowestCommonAncestor(root.right,p,q) //右
|
||||
if left and right: return root //中: left和right不为空,root就是最近公共节点
|
||||
elif left and not right: return left //目标节点是通过left返回的
|
||||
elif not left and right: return right //目标节点是通过right返回的
|
||||
else: return None //没找到
|
||||
if not root or root == p or root == q:
|
||||
return root
|
||||
|
||||
left = self.lowestCommonAncestor(root.left, p, q)
|
||||
right = self.lowestCommonAncestor(root.right, p, q)
|
||||
|
||||
if left and right:
|
||||
return root
|
||||
if left:
|
||||
return left
|
||||
return right
|
||||
```
|
||||
|
||||
## Go
|
||||
|
Reference in New Issue
Block a user