美文网首页
lowest common ancestor

lowest common ancestor

作者: 丁不想被任何狗咬 | 来源:发表于2016-08-16 23:52 被阅读14次

    lca的dfs做法,含判断p q存在性。

    class Solution {
        pair<TreeNode*, int> helper(TreeNode * root, TreeNode * p, TreeNode *q) {
            if(root == NULL) return {NULL, 0};
            auto l = helper(root->left, p, q);
            if(l.first && l.second == 2) { return l;}
            auto r = helper(root->right, p,q);
            if(r.first && r.second == 2) { return r;}
            int count = l.second + r.second;
            if(root == p || root == q) { count++; return {root,count};}
            if(count == 2) {return {root, count};}
            if(l.second == 1) {return l;}
            if(r.second == 1) {return r;}
            return {NULL, 0};
        }
        
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            auto res = helper(root, p, q);
            if(res.second == 2) {return res.first;}
            return NULL;
        }
    };
    

    不含判断:

    class Solution {
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            if(root == NULL || p == NULL || q == NULL) return NULL;
            if(root == p || root == q) return root;
            TreeNode * l = lowestCommonAncestor(root->left, p, q);
            TreeNode * r = lowestCommonAncestor(root->right, p, q);
            if(l && r) return root;
            if(l) return l;
            if(r) return r;
            return NULL;        
        }
    };    
    

    相关文章

      网友评论

          本文标题:lowest common ancestor

          本文链接:https://www.haomeiwen.com/subject/tkxmsttx.html