当前位置:网站首页>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)
边栏推荐
- 让 Rust 库更优美的几个建议!你学会了吗?
- 云原生(三十二) | Kubernetes篇之平台存储系统介绍
- What can be done for traffic safety?
- B站大佬用我的世界搞出卷積神經網絡,LeCun轉發!爆肝6個月,播放破百萬
- 传统企业要为 Web3 和去中心化做的 11 个准备
- Koa2 addition, deletion, modification and query of JSON array
- 儿童睡衣(澳大利亚)AS/NZS 1249:2014办理流程
- 同构+跨端,懂得小程序+kbone+finclip就够了!
- Is "applet container technology" a gimmick or a new outlet?
- 不要再说微服务可以解决一切问题了
猜你喜欢
The method of reinstalling win10 system is as simple as that
传统企业要为 Web3 和去中心化做的 11 个准备
With the help of this treasure artifact, I became the whole stack
What can be done for traffic safety?
koa2对Json数组增删改查
Les entreprises ne veulent pas remplacer un système vieux de dix ans
js對JSON數組的增删改查
Let's see through the network i/o model from beginning to end
公链与私链在数据隐私和吞吐量上的竞争
Experiment 4: installing packages from Gui
随机推荐
传统企业要为 Web3 和去中心化做的 11 个准备
The statement that allows full table scanning does not seem to take effect set odps sql. allow. fullscan=true; I
What should I do if the USB flash disk data is formatted and how can I recover the formatted USB flash disk data?
How can Oracle CDC deserialize with jsondebeziumdeserializationschema
The problem that dockermysql cannot be accessed by the host machine is solved
Is the more additives in food, the less safe it is?
CRMEB 商城系统如何助力营销?
请问async i/o可以由udf算子实现然后用sql api调用吗?目前好像只看到Datastre
每日刷题记录 (十五)
Laravel8 uses passport authentication to log in and generate a token
吴恩达2022机器学习课程评测来了!
mysql-cdc 的jar包 ,在flink运行模式下,是不是要放在不同的地方呢?
Experiment 4: installing packages from Gui
Implementation steps of mysql start log in docker
不要再说微服务可以解决一切问题了
MySQL数据库之JDBC编程
A few suggestions for making rust library more beautiful! Have you learned?
Experiment 6: installing eve-ng
Let's see through the network i/o model from beginning to end
JDBC programming of MySQL database