```
TreeNode* firstCommonAncestor(TreeNode* root, TreeNode* q, TreeNode* p){

if(root == p || root == q){
    return p;
}

if(root == NULL){
    return NULL;
}
TreeNode* temp = firstCommonAncestor(root->left,q,p);
TreeNode* temp1 = firstCommonAncestor(root->right,q,p);

if(temp1 != NULL && temp1 != p){
    return temp1;
}
if(temp != NULL && temp != p){
    return temp;
}

if((temp == NULL && temp1 != NULL)||(temp1 == NULL && temp != NULL)){
    return p;
}

if(temp != NULL && temp1 != NULL){
    return root;
}

return NULL;

}

```

I tested this quite thoroughly and it seems to work but looks quite messy. Can anyone give me input on how to improve the style and the performance?