236. Lowest Common Ancestor of a

2017-11-20  本文已影响0人  larrymusk

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

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;
    

}
上一篇下一篇

猜你喜欢

热点阅读