当前位置:网站首页>剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
2022-07-15 23:18:00 【Ding Jiaxiong】
题目
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]

示例 1:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6
解释: 节点 2 和节点 8 的最近公共祖先是 6。
示例 2:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
输出: 2
解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。
说明:
所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉搜索树中。
题解
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 > p.val and root.val > q.val:
return self.lowestCommonAncestor(root.left,p,q)
return root

边栏推荐
- LCD1602 display key position
- Pay attention to those potential system design problems
- 力扣练习——19 查找和最小的K对数字
- 力扣练习——14 简化路径
- The best time to buy and sell stocks
- 使用堆外内存
- P1088 [noip2004 popularity group question 4] Martians ← next_ permutation
- 2面字节,被面试官抬着走出去,分享给大家
- Ethernet development and testing, have you done this step right (1)
- Breathing lamp circuit based on 555 timer
猜你喜欢
随机推荐
Lombok 介绍
0715 iron ore fell 10%
OLED circularly displays picture text
We overestimate the value of coding
关于线程切换问题的一些思考总结
力扣练习——15 接雨水
笔记
Deployment practice of skywalking test environment
TCmalloc学习
进程同步问题总结
实验三 Servlet 相关技术
你没有抓住 Promises 的要点
C: free(): 无效指针中止(核心转储)的思考
Redis concept, configuration and sentinel high availability of redis
codeforces每日5题(均1500)-第十六天
力扣练习——14 简化路径
Chrome plug-in development
从红魔7S系列看游戏手机的自驱进化
IP静态路由综合实验
Digital display of potentiometer based on ADC0832








![[MySQL must know and know] conditional statement](/img/40/333f3ef4822da00f693ee57c9f5f21.png)
