当前位置:网站首页>75.二叉搜索树额最近公共祖先
75.二叉搜索树额最近公共祖先
2022-06-29 18:29:00 【是乔乔啊】
题目
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
思路
迭代:
1.循环搜索: 当节点 root 为空时跳出;
- 当 p, q都在 root 的 右子树 中,则遍历至 root.right ;
- 否则,当 p, q都在 root 的 左子树中,则遍历至 root.left ;
- 否则,说明找到了 最近公共祖先 ,跳出。
2.返回值: 最近公共祖先 root 。
代码
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
while root:
if root.val < p.val and root.val < q.val: # p,q 都在 root 的右子树中
root = root.right # 遍历至右子节点
elif root.val > p.val and root.val > q.val: # p,q 都在 root 的左子树中
root = root.left # 遍历至左子节点
else: break
return root
边栏推荐
- Error building SqlSession问题
- 源码安装MAVROS
- Source code installation mavros
- 第02章_MySQL的数据目录
- Adobe Premiere foundation - material nesting (animation of Tiktok ending avatar) (IX)
- Adobe Premiere Basics - common video effects (cropping, black and white, clip speed, mirroring, lens halo) (XV)
- Interview question 10.10 Rank of digital stream
- 信息系统项目管理师---第七章项目成本管理历年考题
- How to use an oak camera as a webcam?
- Deep learning --- the weight of the three good students' scores (2)
猜你喜欢
随机推荐
C Primer Plus Chapter 12_ Storage categories, links, and memory management_ Codes and exercises
Sd6.23 summary of intensive training
【网络是怎么连接的】第三章 探索集线器,交换机和路由器
面试题 10.10. 数字流的秩
C Primer Plus 第12章_存储类别、链接和内存管理_代码和练习题
数据分析基础--预测模型
Apache Doris basic usage summary
MySQL 企业级开发规范
Cannot retrieve repository metadata 处理记录
信息系统项目管理师---第七章项目成本管理历年考题
Dragon canvas animation
Goldfish rhca memoirs: do447 build advanced job workflow -- create workflow job template and start workflow job
山东大学项目实训(七)添加导航栏选择城市
Apache inlong million billion level data stream processing
Basis of data analysis -- prediction model
如何使用物联网低代码平台进行服务管理?
Stepping on the pit: json Parse and json stringify
Adobe Premiere foundation - opacity (matte) (11)
Sister Juan takes you to learn database -- 5-day sprint Day1
Travel card "star picking" hot search first! Stimulate the search volume of tourism products to rise









