题目链接:
题解
由于是二叉搜索树,两个节点的最近公共祖先就是从 root 找到第一个 val 在两个节点之间的节点。
参考代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| # # @lc app=leetcode.cn id=235 lang=python3 # # LC235.二叉搜索树的最近公共祖先 #
# @lc code=start # 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': pp = min(p.val, q.val) qq = max(p.val, q.val) def dfs(rt): # print(rt.val, pp, qq) if rt.val >= pp and rt.val <= qq: return rt if rt.val > qq: return dfs(rt.left) if rt.val < pp: return dfs(rt.right) # ans = dfs(root) return dfs(root) # @lc code=end
|