当前位置:网站首页>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)
边栏推荐
- flinksql select id ,count(*) from a group by id .
- [launched in the whole network] redis series 3: high availability of master-slave architecture
- Restoration analysis of protobuf protocol of bullet screen in station B
- Les entreprises ne veulent pas remplacer un système vieux de dix ans
- MySQL数据库之JDBC编程
- Redis persistence mechanism
- Interview question: AOF rewriting mechanism, redis interview must ask!!!
- AI表现越差,获得奖金越高?纽约大学博士拿出百万重金,悬赏让大模型表现差劲的任务...
- MySQL implementation of field segmentation from one line to multiple lines of example code
- 为了交通安全,可以做些什么?
猜你喜欢

Station B Big utilise mon monde pour faire un réseau neuronal convolutif, Le Cun Forward! Le foie a explosé pendant 6 mois, et un million de fois.

(shuttle) navigation return interception: willpopscope

GPT-3当一作自己研究自己,已投稿,在线蹲一个同行评议

The important data in the computer was accidentally deleted by mistake, which can be quickly retrieved by this method

The worse the AI performance, the higher the bonus? Doctor of New York University offered a reward for the task of making the big model perform poorly

How much does the mlperf list weigh when AI is named?

B 站弹幕 protobuf 协议还原分析

If the request URL contains jsessionid, the solution

云原生(三十二) | Kubernetes篇之平台存储系统介绍

【全网首发】Redis系列3:高可用之主从架构的
随机推荐
The important data in the computer was accidentally deleted by mistake, which can be quickly retrieved by this method
The problem of ASP reading Oracle Database
电脑重装系统u盘文件被隐藏要怎么找出来
(shuttle) navigation return interception: willpopscope
The tutorial of computer reinstallation win10 system is simple and easy to understand. It can be reinstalled directly without U disk
What should I do if the USB flash disk data is formatted and how can I recover the formatted USB flash disk data?
Case recommendation: An Qing works with partners to ensure that the "smart court" is more efficient
自动更新Selenium驱动chromedriver
Children's pajamas (Australia) as/nzs 1249:2014 handling process
docker mysql5.7如何设置不区分大小写
How to implement Lua entry of API gateway
What does security capability mean? What are the protection capabilities of different levels of ISO?
吴恩达2022机器学习课程评测来了!
COSCon'22 社区召集令来啦!Open the World,邀请所有社区一起拥抱开源,打开新世界~
How does crmeb mall system help marketing?
Dockermysql modifies the root account password and grants permissions
JS addition, deletion, modification and query of JSON array
CRMEB商城系统如何助力营销?
Efficient ETL Testing
js导入excel&导出excel