Last active
July 23, 2021 18:31
-
-
Save fnalmeidap/134c5736cf547727eebb246bb25babe9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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