Skip to content

Instantly share code, notes, and snippets.

@fnalmeidap
Last active July 23, 2021 18:31
Show Gist options
  • Save fnalmeidap/134c5736cf547727eebb246bb25babe9 to your computer and use it in GitHub Desktop.
Save fnalmeidap/134c5736cf547727eebb246bb25babe9 to your computer and use it in GitHub Desktop.
# Single node definition
struct Node {
int value;
Node *left;
Node *right;
};
class Solution {
public:
Node* LowestCommonAncestor(Node* root, Node* p, Node* q){
if(root){
if(root -> value == p -> value || root -> value == q -> value){
return root;
} else {
auto left = LowestCommonAncestor(root, p, q);
auto right = LowestCommonAncestor(root, p, q);
if( left && right ){
return root;
}
if( left ){
return left;
}
if( right ) {
return right;
}
return nullptr;
}
} else {
return nullptr;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment