Given a Binary Tree with all unique values and two nodes value, n1 and n2. The task is to find the lowest common ancestor of the given two nodes. We may assume that either both n1 and n2 are present in the tree or none of them are present.
classSolution { public: pair<bool, Node*> helper(Node* root, int n1, int n2){ if(!root) return {false, NULL}; if(root->data == n1 or root->data == n2) { auto l = helper(root->left, n1, n2); if(l.first) return {true, root}; auto r = helper(root->right, n1, n2); if(r.first) return {true, root}; return {true, NULL}; } auto l = helper(root->left, n1, n2); if(l.first and l.second) return l; auto r = helper(root->right, n1, n2); if(r.first and r.second) return r; if(l.first and r.first) return {true, root}; return {l.first or r.first, NULL}; } //Function to return the lowest common ancestor in a Binary Tree. Node *lca(Node *root, int n1, int n2){ returnhelper(root, n1, n2).second; } };