当前位置:网站首页>The nearest common ancestor of binary tree
The nearest common ancestor of binary tree
2022-06-11 18:28:00 【HHYX.】
The nearest common ancestor of a binary tree
Topic link : The nearest common ancestor of a binary tree
Title Description
Given a binary tree , Find the nearest common ancestor of the two specified nodes in the tree .
In Baidu Encyclopedia, the most recent definition of public ancestor is :“ For a tree T Two nodes of p、q, The nearest common ancestor is represented as a node x, Satisfy x yes p、q Our ancestors and x As deep as possible ( A node can also be its own ancestor ).”
Topic analysis
For a binary tree , There are many ways to find the nearest common ancestor node , Only one of them is introduced here . According to the meaning , To find the nearest public ancestor node , First, for a node , If p and q In the left and right subtrees of this node , So the node is pq The nearest common ancestor node of . If both nodes are in the left or right subtree of a node , Then you can recursively go to the next node for judgment , Note that a node may be its own ancestor node , namely p Nodes may also be q The ancestor node of the node , Situation judgment is required . The code implementation is as follows :
Code implementation
bool Find(TreeNode* root, TreeNode* key)// lookup key Whether it exists in the subtree of this node
{
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 and q Respectively in root On the left and right subtrees of
{
return root;
}
else if ((leftp && leftq))//p and q On the same left
{
return lowestCommonAncestor(root->left, p, q);
}
else if (rightp && rightq)
{
return lowestCommonAncestor(root->right, p, q);
}
else
{
return nullptr;
}
}

边栏推荐
猜你喜欢
随机推荐
[C语言]压缩字符串并添加标记字符
神经网络与深度学习-2- 机器学习简单示例-PyTorch
求字符串中最大的 3 位相同数字
HashSet集合
viso的常见操作
async导致函数结果出乎意料,改变原来代码的意图;await is only valid in async functions and the top level bodies of modules
TR-069 protocol introduction
Sorted circular linked list
ACL 2022: is it no longer difficult to evaluate word polysemy? A new benchmark "dibimt"
MMA-Self-defining function
How to learn and self-study
Combination sum of 39 questions
[Golang]力扣Leetcode - 292. Nim 游戏(数学)
01.电信_领域业务经验
【无标题】
论催收系统的管理子系统选型设计
SISO Decoder for Repetition(补充章节4)
全志科技T3开发板(4核ARM Cortex-A7)——MQTT通信协议案例
MATLAB 保存imshow绘制图片到指定文件夹中的两种方法
牛客刷题——二叉搜索树与双向链表
![[C语言]用结构体按分数高低降序输出学生的姓名和分数](/img/41/b9dba88941560b296f4d7153b7c684.png)







