当前位置:网站首页>Leetcode 236. 二叉树的最近公共祖先
Leetcode 236. 二叉树的最近公共祖先
2022-08-09 22:05:00 【LuZhouShiLi】
Leetcode 236. 二叉树的最近公共祖先
题目
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
思路
递归出口
- 当越过叶子节点,直接返回null
- 当root等于p,q,直接返回root
递归工作
- 递归左子树
- 递归右子树
- 判断左子树和右子树是否为空
返回值
- 左右子树都不为空,说明左右子树都不包含p,q,返回null
- 当左右子树同时不为空,直接返回root
- 当左右子树有一个为空,另一个不为空,返回不为空的那个
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || root == p || root == q)
{
return root;
}
// 递归左子树
TreeNode *l = lowestCommonAncestor(root->left,p,q);
// 递归右子树
TreeNode *r = lowestCommonAncestor(root->right,p,q);
if(l == nullptr)
{
// 左子树为空 p q 在右子树中
return r;
}
if(r == nullptr)
{
return l;// 右子树为空 pq 在左子树中
}
return root;
}
};
边栏推荐
- 量化交易接口系统有哪些稳定性?
- Sun Zhengyi lost 150 billion: it was expensive at the beginning
- OSS文件上传
- Leetcode.25 K个一组翻转链表(模拟/递归)
- Chapter 15 HMM模型
- PyQt5:入门使用教程
- C 在函数声明前加typedef
- EasyExcel使用
- R语言ggstatsplot包grouped_ggscatterstats函数可视化分组散点图、并添加假设检验结果(包含样本数、统计量、效应大小及其置信区间、显著性、组间两两比较、贝叶斯假设)
- Bi Sheng Compiler Optimization: Lazy Code Motion
猜你喜欢
第十七期八股文巴拉巴拉说(数据库篇)
力扣 1413. 逐步求和得到正数的最小值
EasyExcel使用
(转)FreeType字体位图属性
shell数组
十步以内,用小程序快速生成App!
【Burning】It's time to show your true strength!Understand the technical highlights of the 2022 Huawei Developer Competition in one article
The 2022-8-9 sixth group of input and output streams
chart.js面积图曲线图统计插件
Kubernetes Service对象
随机推荐
xlrd 与 xlsxwritter 的基本操作
【GORM】模型关系-HasMany关系
华为鸿蒙3.0的野望:技术、应用、生态
Flutter 绘制美不胜收的光影流动效果
十步以内,用小程序快速生成App!
少儿编程 电子学会图形化编程等级考试Scratch三级真题解析(判断题)2022年6月
迁移学习 & 凯明初始化
ArrayList 和 LinkedList 区别
p5.js实现的炫酷星体旋转动画
PyQt5:入门使用教程
Basic operations of xlrd and xlsxwriter
Qt 消息机制和事件
Interviewer: How to deal with Redis big key?
Tencent continues to wield the "big knife" to reduce costs and increase efficiency, and free catering benefits for outsourced employees have been cut
如何坚持使用程序化系统?
leetcode:332. 重新安排行程
c:forEach varStatus属性
反射机制篇
月薪5K的运维小白如何成为月薪5W的高级架构师?
mysql中的key是怎么用的,或者这个值有什么意义,如下图?