【leetcode】最近公共祖先

1、二叉搜索树的最近公共祖先

https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
排序的,如果root大小在p,q之间,说明root就是祖先。
如果root大于p,q,说明最近公共祖先在root左子树上;
如果root小于p,q,说明最近公共祖先在root右子树上。

class Solution {
public:
    TreeNode* res;
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if((root->val - p->val) * (root->val - q->val) <= 0)
            res = root;
        else if(root->val < p->val && root->val < q->val)
            return lowestCommonAncestor(root->right,p,q);
        else
            return lowestCommonAncestor(root->left,p,q);
        return res;
    }    
};

2、二叉树的最近公共祖先

https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
普通二叉树,则是后序遍历,先遍历左右,然后对root进行比较

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == NULL)
            return root;
        if(root == p || root == q)
            return root;
        TreeNode* rleft = lowestCommonAncestor(root->left, p, q);
        TreeNode* rright = lowestCommonAncestor(root->right, p, q);
        if(rleft != NULL && rright != NULL)
            return root;
        else if(rright != NULL)
            return rright;
        else
            return rleft;
        return NULL;
    }
};
发布了178 篇原创文章 · 获赞 30 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/ACBattle/article/details/89482247