Merge pull request #763 from RyouMon/master

修复 0236.二叉树的最近公共祖先.md/0235.二叉搜索树的最近公共祖先.md Python3解法
This commit is contained in:
程序员Carl
2021-09-20 09:47:58 +08:00
committed by GitHub
2 changed files with 32 additions and 14 deletions

View File

@@ -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