当前位置:网站首页>剑指 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
边栏推荐
- The method of solving stored procedure table name passing through variable in mysql
- 风险策略调优中重要的三步分析法
- 时时刻刻保持敬畏之心
- Typescript22 - interface inheritance
- Pyspark Machine Learning: Vectors and Common Operations
- Four implementations of
batch insert: have you really got it? - Immutable
- Difference Between Compiled and Interpreted Languages
- typescript26 - literal types
- The maximum quantity leetcode6133. Grouping (medium)
猜你喜欢
Simple and easy to use task queue - beanstalkd
Unknown Bounded Array
JS new fun(); class and instance JS is based on object language Can only act as a class by writing constructors
Article summary: the basic model of VPN and business types
Four implementations of
batch insert: have you really got it? Software Testing Interview (3)
数组问题之《两数之和》以及《三数之和 》
【愚公系列】2022年07月 Go教学课程 023-Go容器之列表
API Design Notes: The pimpl trick
Pyspark Machine Learning: Vectors and Common Operations
随机推荐
safari浏览器怎么导入书签
A way to deal with infinite debugger
Excel record of integer programming optimization model to solve the problem
Interview Blitz 69: Is TCP Reliable?Why?
律师解读 | 枪炮还是玫瑰?从大厂之争谈元宇宙互操作性
typescript23-元组
报错:AttributeError: module ‘matplotlib’ has no attribute ‘figure’
UE4 从鼠标位置射出射线检测
【kali-信息收集】枚举——DNS枚举:DNSenum、fierce
程序员代码面试指南 CD15 生成窗口最大值数组
数组问题之《两数之和》以及《三数之和 》
怀念故乡的月亮
typescript25-类型断言
JS new fun(); class and instance JS is based on object language Can only act as a class by writing constructors
解决ffmpeg使用screen-capture-recorder录屏,有屏幕缩放的情况下录不全的问题
Mysql基础篇(Mysql数据类型)
Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink
Article summary: the basic model of VPN and business types
scheduleWithFixedDelay和scheduleAtFixedRate的区别
25. Have you been asked these three common interview questions?