【LeetCode】二叉树的最近公共祖先

二叉树的最近公共祖先

      • 题目描述
      • 算法分析
      • 编程代码
      • 方法二:
      • 算法分析
      • 编程代码

链接: 二叉树的最近公共祖先

题目描述

【LeetCode】二叉树的最近公共祖先_第1张图片

算法分析

【LeetCode】二叉树的最近公共祖先_第2张图片

编程代码

/**
 * 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;
        }
    }
};

【LeetCode】二叉树的最近公共祖先_第3张图片

方法二:

算法分析

【LeetCode】二叉树的最近公共祖先_第4张图片

编程代码

/**
 * 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;
    }
};

【LeetCode】二叉树的最近公共祖先_第5张图片

你可能感兴趣的:(leetcode,leetcode)