当前位置:网站首页>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)
边栏推荐
- How to implement Lua entry of API gateway
- 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
- Dayu200 experience officer runs the intelligent drying system page based on arkui ETS on dayu200
- Face recognition class attendance system based on paddlepaddle platform (easydl)
- Word2vec (skip gram and cbow) - pytorch
- mysql连接vscode成功了,但是报这个错
- COSCon'22 社区召集令来啦!Open the World,邀请所有社区一起拥抱开源,打开新世界~
- 吴恩达2022机器学习课程评测来了!
- Detailed explanation of regular expression (regexp) in MySQL
- Isomorphism + cross end, knowing applet +kbone+finclip is enough!
猜你喜欢

Bipartite graph determination

asp读取oracle数据库问题

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

人均瑞数系列,瑞数 4 代 JS 逆向分析

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.

Gpt-3 is a peer review online when it has been submitted for its own research
The problem that dockermysql cannot be accessed by the host machine is solved
Dockermysql modifies the root account password and grants permissions

Knowledge * review

mysql连接vscode成功了,但是报这个错
随机推荐
资产安全问题或制约加密行业发展 风控+合规成为平台破局关键
(shuttle) navigation return interception: willpopscope
The problem that dockermysql cannot be accessed by the host machine is solved
Dockermysql modifies the root account password and grants permissions
前置机是什么意思?主要作用是什么?与堡垒机有什么区别?
How can Oracle CDC deserialize with jsondebeziumdeserializationschema
Wu Enda 2022 machine learning course evaluation is coming!
为了交通安全,可以做些什么?
实现多彩线条摆出心形
每日刷题记录 (十五)
[launched in the whole network] redis series 3: high availability of master-slave architecture
借助这个宝藏神器,我成为全栈了
Gradle知识概括
TDengine 社区问题双周精选 | 第二期
Master binary tree in one article
js对JSON数组的增删改查
(1) Chang'an chain learning notes - start Chang'an chain
MySQL实现字段分割一行转多行的示例代码
docker启动mysql及-eMYSQL_ROOT_PASSWORD=my-secret-pw问题解决
How to choose indoor LED display? These five considerations must be taken into account