基于广义公共祖先的递归
文章目录
这里主要描述的是对官方题解的一种理解方式,我个人对官方题解的理解比较吃力,因此给出了一个我自己能够想得通的理解过程。如果能够直接理解官解的思路的话,建议不用看我这个,看我这个纯属浪费时间
另外该文章也同步发表于 leetcode 题解:点此访问
题目说明
暴力法
如果要使用后序遍历解题,最容易想到的是暴力方法,先整一个函数检查以 root 为节点的二叉树是否含有某一给定节点 node
bool checkNodeExist(TreeNode* root, TreeNode* node)
{
if(root == nullptr)
{
return false;
}
if(root == node)
{
return true;
}
else
{
return checkNodeExist(root->left, node) || checkNodeExist(root->right, node);
}
}
然后开始后序遍历,先检查左子树,再检查右子树,最后检查 root
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// root 为 null,返回
if(root == nullptr)
{
return nullptr;
}
TreeNode* ancestor = nullptr;
// 检查左子树中是否存在公共祖先
ancestor = lowestCommonAncestor(root->left, p, q);
if(ancestor)
{
return ancestor;
}
// 检查右子树中是否存在公共祖先
ancestor = lowestCommonAncestor(root->right, p, q);
if(ancestor)
{
return ancestor;
}