当前位置:网站首页>剑指 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边栏推荐
- 数组问题之《下一个排列》、《旋转图像》以及二分查找之《搜索二维矩阵》
- Advice given by experts with four years of development experience in Flutter tutorial
- 产品经理访谈 | 第五代验证码的创新与背景
- lambda
- 基于STM32设计的UNO卡牌游戏(双人、多人对战)
- TypeScript简化运行之ts-node
- safari浏览器怎么导入书签
- "ArchSummit: The cry of the times, technical people can hear"
- scheduleWithFixedDelay和scheduleAtFixedRate的区别
- typescript22-接口继承
猜你喜欢

UE4 制作遇到的问题

认真对待每一个时刻

Software Testing Interview (3)

【kali-信息收集】枚举——DNS枚举:DNSenum、fierce

Weekly Summary (*67): Why not dare to express an opinion

深圳某游戏研发公司给每个工位都装监控,网友:堪比坐牢!

出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法

High Numbers | 【Re-integration】Line Area Score 880 Examples

Mysql基础篇(约束)
![Invalid classes inferred from unique values of `y`. Expected: [0 1 2], got [1 2 3]](/img/53/3dc2233498db78b8480084ce496f0b.png)
Invalid classes inferred from unique values of `y`. Expected: [0 1 2], got [1 2 3]
随机推荐
动态规划 01背包
Mysql基础篇(约束)
Progressive Reconstruction of Visual Structure for Image Inpainting 论文笔记
出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法
风险策略调优中重要的三步分析法
Game Theory (Depu) and Sun Tzu's Art of War (42/100)
[FPGA tutorial case 43] Image case 3 - image sobel edge extraction through verilog, auxiliary verification through MATLAB
数据比对功能调研总结
PMP工具与技术总结
Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink
typescript24-类型推论
【愚公系列】2022年07月 Go教学课程 023-Go容器之列表
MySQL3
在沈自所的半年总结
TypeScript简化运行之ts-node
typescript20-接口
typescript26 - literal types
Optional parameters typescript19 - object
[kali-information collection] enumeration - DNS enumeration: DNSenum, fierce
一个往年的朋友
https://leetcode.cn/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/