1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| # @Title: 二叉搜索树的最近公共祖先 (二叉搜索树的最近公共祖先 LCOF)
# @Author: 15816537946@163.com
# @Date: 2022-02-20 19:06:28
# @Runtime: 76 ms
# @Memory: 19 MB
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
if root.val > q.val and root.val > p.val:
return self.lowestCommonAncestor(root.left,p,q)
return root
|