当前位置:网站首页>力扣刷题——二叉树的最近公共祖先
力扣刷题——二叉树的最近公共祖先
2022-06-11 18:14:00 【HHYX.】
题目链接:二叉树的最近公共祖先
题目描述
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
题目分析
对于一棵二叉树,要想找到最近的公共祖先节点有很多办法,这里仅介绍其中一种。根据题意,要找最近的公共祖先节点,首先对于一个节点,如果p和q分别在该节点的左右子树中,那么该节点就是pq的最近公共祖先节点。如果两个节点都在某个节点的左子树或者右子树中,那么可以递归进下一个节点进行判断,这里需要注意的是一个节点可能是他自己的祖先节点,即p节点可能也是q节点的祖先节点,需要进行情况判断。代码实现如下:
代码实现
bool Find(TreeNode* root, TreeNode* key)//查找key是否存在于该节点的子树中
{
if (root == nullptr)
{
return false;
}
if (root == key)
{
return true;
}
return Find(root->left, key) || Find(root->right, key);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
bool leftp = Find(root->left, p);
bool rightp = Find(root->right, p);
bool leftq = Find(root->left, q);
bool rightq = Find(root->right, q);
if (root == p || root == q)
{
return root;
}
else if ((leftp && rightq)||(rightp && leftq))//p和q分别在root的左右子树上
{
return root;
}
else if ((leftp && leftq))//p和q在同一左侧
{
return lowestCommonAncestor(root->left, p, q);
}
else if (rightp && rightq)
{
return lowestCommonAncestor(root->right, p, q);
}
else
{
return nullptr;
}
}

边栏推荐
猜你喜欢
随机推荐
【无标题】
Database lock and transaction isolation level
VIM common commands
TR-069 protocol introduction
[C语言]用结构体把最高分的学生输出,可有多个最高分
力扣23题,合并K个升序链表
Function and principle of key in V-for
[c language] limit the number of searches and output the maximum value found in the number of internal searches
Getting started with CTF
ACL 2022: is it no longer difficult to evaluate word polysemy? A new benchmark "dibimt"
EditText 金额限制
Feign 共享登录信息进行请求
Monitoring loss functions using visdom
[golang] leetcode - 292 Nim games (Mathematics)
力扣31 下一个排列
Use egg Js+mongodb simple implementation of curdapi
ctfhub-sql布尔盲注
Oracle高级数据库复习
软件需求工程复习
Experiment 2: write a program and verify that the linear table sequence represents all operations


![[c language] compress strings and add markup characters](/img/b7/f7918f3ee0c409faffc70addd5ee65.png)





