美文网首页
236. Lowest Common Ancestor of a

236. Lowest Common Ancestor of a

作者: larrymusk | 来源:发表于2017-11-20 22:58 被阅读0次

    采用递归,分别在左子树和右子树里面查找,如果都能找到,当前节点就是最近共同祖先
    如果只能在一个树找到,说明这个数就是最近共同祖先

    struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
        
        
        if(root == NULL || root == p || root == q)
            return root;
    
        struct TreeNode *left = lowestCommonAncestor(root->left, p,q);
        struct TreeNode *right = lowestCommonAncestor(root->right, p,q);
    
        if(left&&right)
            return root;
        if(left)
            return left;
        if(right)
            return right;
    
        return NULL;
        
    
    }

    相关文章

      网友评论

          本文标题:236. Lowest Common Ancestor of a

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