LCR 194.二叉树的最近公共祖先

题目来源:

        leetcode题目,网址:LCR 194. 二叉树的最近公共祖先 - 力扣(LeetCode)

解题思路:

        获得从根节点到两节点的链路后,返回最后一个相同的节点即可。

解题代码:

/**
 * 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) {
        stack<TreeNode*> stackp=getStack(root,p);
        stack<TreeNode*> stackq=getStack(root,q);
        TreeNode* res;
        while(stackq.top()==stackp.top()){
            cout<<stackq.size()<<" "<<stackp.size()<<endl;
            res=stackq.top();
            stackp.pop();
            stackq.pop();
            if(stackq.size()==0 || stackp.size()==0){
                break;
            }
        }
        return res;
    }
    stack<TreeNode*> getStack(TreeNode*root,TreeNode* pur){
        stack<TreeNode*> res;
        if(root==nullptr){
            return res;
        }
        if(root==pur){
            res.push(root);
            return res ;
        }
        res=getStack(root->left,pur);
        if(res.size()!=0){
            res.push(root);
            return res;
        }
        res=getStack(root->right,pur);
        if(res.size()!=0){
            res.push(root);
            return res;
        }        
        return res;
    }
};
 

总结:

        官方题解给出了两种解法。第一种是逐个节点判断当前节点,当前节点的左子树,当前节点的右子树是否包含两个目标节点,最后一个找到的符合要求的节点即为所求。第二种获得链路后求相同节点。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值