一、题目描述:236. 二叉树的最近公共祖先(中等)
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
示例 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。因为根据定义最近公共祖先节点可以为节点本身。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解题思路
方法一
这种方法非常直观。先深度遍历改树。当你遇到节点 p 或 q 时,返回一些布尔标记。该标志有助于确定是否在任何路径中找到了所需的节点。最不常见的祖先将是两个子树递归都返回真标志的节点。它也可以是一个节点,它本身是p或q中的一个,对于这个节点,子树递归返回一个真标志。让我们看看基于这个想法的形式算法。
算法:
从根节点开始遍历树。
如果当前节点本身是 p 或 q 中的一个,我们会将变量 mid 标记为 true,并继续搜索左右分支中的另一个节点。
如果左分支或右分支中的任何一个返回 true,则表示在下面找到了两个节点中的一个。
如果在遍历的任何点上,左、右或中三个标志中的任意两个变为 true,这意味着我们找到了节点 p 和 q 的最近公共祖先。
方法二:使用父指针迭代
如果每个节点都有父指针,那么我们可以从 p 和 q 返回以获取它们的祖先。在这个遍历过程中,我们得到的第一个公共节点是 LCA 节点。我们可以在遍历树时将父指针保存在字典中。算法:
从根节点开始遍历树。
在找到 p 和 q 之前,将父指针存储在字典中。
一旦我们找到了 p 和 q,我们就可以使用父亲字典获得 p 的所有祖先,并添加到一个称为祖先的集合中。
同样,我们遍历节点 q 的祖先。如果祖先存在于为 p 设置的祖先中,这意味着这是 p 和 q 之间的第一个共同祖先(同时向上遍历),因此这是 LCA 节点。
方法三、
1、建立两个数组p1,q1遍历保存p,q的路径,一个栈stack保存当前遍历节点的路径,当当前节点为q的时候p1 = stack,当当前节点为q的时候q1=stack。
2、p1和q1找之后从头开始找到最后一个相同的节点,这个节点就是p,q最近公共祖先
三、代码
方法一、
class Solution:
def __init__(self):
# Variable to store LCA node.
self.ans = None
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
def recurse_tree(current_node):
# If reached the end of a branch, return False.
if not current_node:
return False
# Left Recursion
left = recurse_tree(current_node.left)
# Right Recursion
right = recurse_tree(current_node.right)
# If the current node is one of p or q
mid = current_node == p or current_node == q
# If any two of the three flags left, right or mid become True.
if mid + left + right >= 2:
self.ans = current_node
# Return True if either of the three bool values is True.
return mid or left or right
# Traverse the tree
recurse_tree(root)
return self.ans
方法二、
stack = [root]
# Dictionary for parent pointers
parent = {root: None}
# Iterate until we find both the nodes p and q
while p not in parent or q not in parent:
node = stack.pop()
# While traversing the tree, keep saving the parent pointers.
if node.left:
parent[node.left] = node
stack.append(node.left)
if node.right:
parent[node.right] = node
stack.append(node.right)
# Ancestors set() for node p.
ancestors = set()
# Process all ancestors for node p using parent pointers.
while p:
ancestors.add(p)
p = parent[p]
# The first ancestor of q which appears in
# p's ancestor set() is their lowest common ancestor.
while q not in ancestors:
q = parent[q]
return q
方法三、
/**
* 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 == NULL)
{
return NULL;
}
vector<TreeNode * > p1;
vector<TreeNode * > q1;
vector<TreeNode * > stack;
lowestCommonAncestor(root, p, q,stack,p1,q1);
int i =0;
for(;i<p1.size() && i<q1.size();i++)
{
if(p1[i] != q1[i])
break;
}
if(i == 0)
return p1[0];
return p1[i-1];
}
void lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q,vector<TreeNode * > & stack,vector<TreeNode*> & p1,vector<TreeNode*> & q1)
{
if(root == NULL)
return;
stack.push_back(root);
if(root == p)
{
p1= stack;
}
if(root == q)
{
q1= stack;
}
if(p1.size() > 0 && q1.size() > 0)
return;
if(root->left != NULL)
{
lowestCommonAncestor(root->left, p, q,stack,p1,q1);
}
if(root->right != NULL)
{
lowestCommonAncestor(root->right, p, q,stack,p1,q1);
}
stack.pop_back();
}
};