Lowest Common Ancestor in Binary Trees
Lowest Common Ancestor in Binary Trees
Finding the lowest common ancestor
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL) return NULL;
else if (find(root->left, p) && find(root->left, q))
return lowestCommonAncestor(root->left, p, q);
else if (find(root->right, p) && find(root->right, q))
return lowestCommonAncestor(root->right, p, q);
else return root;
}
private:
bool find(TreeNode* node, TreeNode* search) {
if (node == NULL) return false;
else if (node == search) return true;
else {
return find(node->left, search) || find(node->right, search);
}
}
};A cleaner solution
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
// Return root if found in both subtrees, otherwise return the side where found
return !left ? right : !right ? left : root;
}#tree