当前位置:网站首页>剑指 Offer 68 - II. 二叉树的最近公共祖先
剑指 Offer 68 - II. 二叉树的最近公共祖先
2022-08-01 04:45:00 【愈努力俞幸运】
考虑通过递归对二叉树进行先序遍历,当遇到节点 p或 q 时返回。从底至顶回溯,当节点 p, q 在节点 root的异侧时,节点 root 即为最近公共祖先,则向上返回 root 。
想上回溯什么?
递归解析:
终止条件:
当越过叶节点,则直接返回 null ;
当 root等于 p,或q,则直接返回 root ;
递推工作:
开启递归左子节点,返回值记为 left ;
开启递归右子节点,返回值记为 right ;
返回值: 根据 left 和 right,可展开为四种情况;
1.当 left 和 right同时为空 :说明 root的左 / 右子树中都不包含 p,q,返回 null ;
2.当 left和 right 同时不为空 :说明 p, q分列在 root的 异侧 (分别在 左 / 右子树),因此 root 为最近公共祖先,返回 root ;
3. 当 left为空 ,right 不为空 :p,q都不在 root的左子树中,直接返回 right。具体可分为两种情况:
(1)p,q其中一个在 root的 右子树 中,假设为p, 此时 right 指向 p;
(2)p,q两节点都在 rootroot 的 右子树 中,此时的 right指向 最近公共祖先节点 ;
4.当 left不为空 , right为空 :与情况 3. 同理;
class Solution:
def lowestCommonAncestor(self, root, p, q):
if not root or root==p or root==q:
return root
left=self.lowestCommonAncestor(root.left,p,q)
right=self.lowestCommonAncestor(root.right, p, q)
if not left and not right:
return
if not left and right:
return right
if not right and left:
return left
return root
边栏推荐
- Simple and easy to use task queue - beanstalkd
- 数据比对功能调研总结
- Unknown Bounded Array
- Difference Between Compiled and Interpreted Languages
- 智芯传感输液泵压力传感器 为精准智能控制注入科技“强心剂”
- typescript27 - what about enumeration types
- typescript24-类型推论
- 故乡的素描画
- Pyspark机器学习:向量及其常用操作
- Weekly Summary (*67): Why not dare to express an opinion
猜你喜欢
博客系统(完整版)
This article takes you to understand the past and present of Mimir, Grafana's latest open source project
typescript19-对象可选参数
这里有110+公开的专业数据集
typescript28-枚举类型的值以及数据枚举
56:第五章:开发admin管理服务:9:开发【文件上传到,MongoDB的GridFS中,接口】;(把文件上传到GridFS的SOP)
High Numbers | 【Re-integration】Line Area Score 880 Examples
The maximum quantity leetcode6133. Grouping (medium)
【无标题】
律师解读 | 枪炮还是玫瑰?从大厂之争谈元宇宙互操作性
随机推荐
PMP 项目沟通管理
【目标检测】YOLOv7理论简介+实践测试
罗技鼠标体验记录
项目风险管理必备内容总结
PMP 项目资源管理
请问shake数据库中想把源的db0的数据同步到目的db5,参数怎么设置呢?
雪糕和轮胎
Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink
Game Theory (Depu) and Sun Tzu's Art of War (42/100)
PMP 项目质量管理
leetcode6132. Make all elements in an array equal to zero (simple, weekly)
Risk strategy important steps of tuning method
基于STM32设计的UNO卡牌游戏(双人、多人对战)
干货!如何使用仪表构造SRv6-TE性能测试环境
在沈自所的半年总结
lambda
/etc/fstab
7 行代码搞崩溃 B 站,原因令人唏嘘!
出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法
云服务器下载安装mongo数据库并远程连接详细图文版本(全)