二叉树的公共祖先【C++】

博客围绕力扣上二叉树的最近公共祖先问题展开。提出两种思路,一是若为三叉链可转换成链表相交问题;二是依据公共祖先特征,即两节点分别在左右子树时该节点为公共祖先。解决方案是用DFS求节点路径并转换成路径相交问题。

236. 二叉树的最近公共祖先 - 力扣(LeetCode)

思路一:如果三叉链 (每个节点有parent)转换成链表相交问题

/**
 * 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:
    bool IsInTree(TreeNode* root,TreeNode* x)
    {
        if(root == nullptr)
            return false;
        if(root == x)
            return true;
        return IsInTree(root->left, x) || IsInTree(root->right, x);
    }
    
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == nullptr)
            return nullptr;
        //p或q是根,另一个是孩子,root就是最近公共祖先
        if(p==root||q==root)
            return root;
        bool pInleft = IsInTree(root->left, p);
        bool pInright = !pInleft;
        bool qInleft = IsInTree(root->left, q);
        bool qInright = !qInleft;
        //1.一个在我的左树,一个在我的右树,我就是最近公共祖先
        //2.都在左,转换成子问题,在左子树去找公共祖先
        //3.都在右,就转换成子问题,在右子树去找公共祖先
        if((pInleft && qInright) || (qInleft && pInright))
        {
            return root;
        }
        else if(pInleft && qInleft)
            return lowestCommonAncestor(root->left, p, q);
        else
            return lowestCommonAncestor(root->right, p, q);
        
    }
       
};

 思路二:公共祖先的特征:如果一个在我的左子树,一个在我的右子树,我就是公共祖先

解决方案:DFS求出p和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:
    bool GetPath(TreeNode* root,TreeNode* x, stack<TreeNode*>& path)
    {
        if(root == nullptr)
            return false;
        path.push(root);
        if(root == x)
            return true;
        if(GetPath(root->left,x,path))
            return true;
        if(GetPath(root->right,x,path))
            return true;
        path.pop();
        return false;
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        stack<TreeNode*> pPath, qPath;
        GetPath(root,p,pPath);
        GetPath(root,q,qPath);
        while(pPath.size()!= qPath.size())
        {
            if(pPath.size()>qPath.size())
            {
                pPath.pop();
            }
            else
            {
                qPath.pop();
            }
        }
        while(pPath.top()!=qPath.top())
        {
            pPath.pop();
            qPath.pop();
        }
        return pPath.top();
    }
};

​

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值