Created
September 29, 2019 22:48
-
-
Save whimbree/966c117ec82fd85597bdaa89e265b195 to your computer and use it in GitHub Desktop.
Lowest Common Ancestor of BST (Black Magic Recursion)
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
class Solution { | |
public: | |
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { | |
if (!root) return nullptr; | |
if (root->val == p->val || root->val == q->val) return root; | |
TreeNode* left = lowestCommonAncestor(root->left, p, q); | |
TreeNode* right = lowestCommonAncestor(root->right, p, q); | |
if (!left) return right; | |
if (!right) return left; | |
return root; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment