【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:

    bool find(TreeNode* tree,TreeNode* x)
    {
        if(tree == nullptr)
        {
            return false;
        }

        return tree == x || find(tree->left,x) || find(tree->right,x);
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == nullptr)
        {
            return nullptr;
        }
        if(root == p || root == q)
        {
            return root;
        }
        bool pLeft,pRight,qLeft,qRight;
        pLeft = find(root->left,p);
        pRight = !pLeft;
        qLeft = find(root->left,q);
        qRight = !qLeft;
        if(pLeft && qLeft)
        {
            return lowestCommonAncestor(root->left,p,q);
        }
        else if(qRight && pRight)
        {
            return lowestCommonAncestor(root->right,p,q);
        }
        else{
            return root;
        }
    }
};

在这里插入图片描述

方法二:

算法分析

在这里插入图片描述

编程代码

/**
 * 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 _Find(TreeNode* root,TreeNode* node,stack<TreeNode*>& st)
    {
        if(root == nullptr)
        {
            return false;
        }

        st.push(root);

        if(root == node)
        {
            return true;
        }

        if(_Find(root->left,node,st))
        {
            return true;
        }

        if(_Find(root->right,node,st))
        {
            return true;
        }
        st.pop();
        return false;
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        stack<TreeNode*> st1;
        stack<TreeNode*> st2;
        _Find(root,p,st1);
        _Find(root,q,st2);

        while(st1.size() > st2.size())
        {
            st1.pop();
        }
        while(st1.size() < st2.size())
        {
            st2.pop();
        }
        while(st1.size() && st2.size())
        {
            if(st1.top() != st2.top())
            {
                st1.pop();
                st2.pop();
            }
            else
            {
                return st2.top();
            }
        }
        return nullptr;
    }
};

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值