当前位置:网站首页>leetcode:236. 二叉树的最近公共祖先
leetcode:236. 二叉树的最近公共祖先
2022-07-06 15:53:00 【uncle_ll】
236. 二叉树的最近公共祖先
来源:力扣(LeetCode)
链接: https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
示例 1:
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出:3
解释:节点 5 和节点 1 的最近公共祖先是节点 3 。
示例 2:
输入:root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出:5
解释:节点 5 和节点 4 的最近公共祖先是节点 5 。因为根据定义最近公共祖先节点可以为节点本身。
示例 3:
输入:root = [1,2], p = 1, q = 2
输出:1
提示:
- 树中节点数目在范围 [2, 1 0 5 10^5 105] 内。
- − 1 0 9 -10^9 −109 <= Node.val <= 1 0 9 10^9 109
- 所有 Node.val 互不相同 。
- p != q
- p 和 q 均存在于给定的二叉树中。
解法
- 递归: 先从根节点开始判断,如果根节点为空,或者某个查找元素为根节点,直接返回根节点;然后递归查找左子树,右子树,如果两个子树查找结果都不为空,表明p,q待查找的两个元素与左子树的根节点或者右子树的根节点相同,则二者的公共节点为该树的根节点;如果有一个子树的查找为空,则返回另外一个子树的查找结果;
代码实现
递归
python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return root
if root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right: # 二个子树的查找结果都不为空,说明拍,
return root
return left if left else right
c++实现
/** * 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)
return root;
if (p == root || q == root)
return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != nullptr && right != nullptr)
return root;
return left != nullptr ? left : right;
}
};
复杂度分析
- 时间复杂度: O ( N ) O(N) O(N)
- 空间复杂度: O ( N ) O(N) O(N)
边栏推荐
- Graphite document: four countermeasures to solve the problem of enterprise document information security
- 请问oracle-cdc用JsonDebeziumDeserializationSchema反序列化
- JS import excel & Export Excel
- How does crmeb mall system help marketing?
- With the help of this treasure artifact, I became the whole stack
- 人均瑞数系列,瑞数 4 代 JS 逆向分析
- Why are some people still poor and living at the bottom of society even though they have been working hard?
- mysql查看表结构的三种方法总结
- mysql拆分字符串作为查询条件的示例代码
- Gradle知识概括
猜你喜欢
Nftscan Developer Platform launches Pro API commercial services
AI金榜题名时,MLPerf榜单的份量究竟有多重?
koa2对Json数组增删改查
今日睡眠质量记录78分
PDF批量拆分、合并、书签提取、书签写入小工具
MySQL connected vscode successfully, but this error is reported
js对JSON数组的增删改查
浅谈现在的弊端与未来的发展
Implementation steps of mysql start log in docker
Daily question brushing record (XV)
随机推荐
Face recognition class attendance system based on paddlepaddle platform (easydl)
Huawei cloud gaussdb (for redis) unveils issue 21: using Gauss redis to achieve secondary indexing
CRMEB商城系统如何助力营销?
How to choose indoor LED display? These five considerations must be taken into account
Today's sleep quality record 78 points
机器人材料整理中的套-假-大-空话
每人每年最高500万经费!选人不选项目,专注基础科研,科学家主导腾讯出资的「新基石」启动申报...
(flutter2) as import old project error: inheritfromwidgetofexacttype
让 Rust 库更优美的几个建议!你学会了吗?
石墨文档:4大对策解决企业文件信息安全问题
资产安全问题或制约加密行业发展 风控+合规成为平台破局关键
Nftscan Developer Platform launches Pro API commercial services
Up to 5million per person per year! Choose people instead of projects, focus on basic scientific research, and scientists dominate the "new cornerstone" funded by Tencent to start the application
mysql查看表结构的三种方法总结
asp读取oracle数据库问题
Why are some people still poor and living at the bottom of society even though they have been working hard?
请问oracle-cdc用JsonDebeziumDeserializationSchema反序列化
Docker starts MySQL and -emysql_ ROOT_ Password = my secret PW problem solving
Dayu200 experience officer homepage AITO video & Canvas drawing dashboard (ETS)
NFTScan 开发者平台推出 Pro API 商业化服务