lettcode.236二叉树的最近公共祖先

lettcode.236二叉树的最近公共祖先

公共祖先

在这里插入图片描述

解法一

我们找规律后会发现, 节点p和节点q分别在公共节点的左右子树中,因此我们可以分三种情况讨论:

  • 当p、q节点都在root的左子树中时,那就递归到root->left中找
  • 当p、q节点都在root的右子树中时,那就递归到root->right中找
  • 当p、q节点在root的左、右子树中或者root等于p、q中的一个节点时,就返回root
bool isIntree(TreeNode* root,TreeNode* x)
    {
        if(root == nullptr)
            return false;
        if(x == root)
            return true;
        
        return isIntree(root->left,x) || isIntree(root->right,x);
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == p || root == q)
            return root;
        bool pInleft = isIntree(root->left,p);
        bool pInright = !pInleft;
        bool qInleft = isIntree(root->left,q);
        bool qInright = !qInleft;

        if(pInleft&&qInright ||qInleft&&pInright)
            return root;
        if(pInleft && qInleft)
            return lowestCommonAncestor(root->left,p,q);
        if(pInright && qInright)
            return lowestCommonAncestor(root->right,p,q);

        return nullptr;
    }

解法二

我们可以使用两个stack分别来记录从根节点到p、q节点的路径,记为pPathqPath当两条路径长度不同时,使较长路径不断pop,然后两条路径同时pop,直到pPath.top() == qPath.top()

bool findPath(stack<TreeNode*>& path,TreeNode* x,TreeNode* root)
    {
        if(root == nullptr)
            return false;
        path.push(root);
        if(root == x)
            return true;
        if(findPath(path,x,root->left))
            return true;
…            pPath.pop();
            qPath.pop();
        }
        return pPath.top();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值