Skip to content

Instantly share code, notes, and snippets.

@whimbree
Created September 29, 2019 22:48
Show Gist options
  • Save whimbree/966c117ec82fd85597bdaa89e265b195 to your computer and use it in GitHub Desktop.
Save whimbree/966c117ec82fd85597bdaa89e265b195 to your computer and use it in GitHub Desktop.
Lowest Common Ancestor of BST (Black Magic Recursion)
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