TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return NULL;
if (root == p  root == q) return root;
TreeNode *L = lowestCommonAncestor(root>left, p, q);
TreeNode *R = lowestCommonAncestor(root>right, p, q);
if (L && R) return root; // if p and q are on both sides
return L ? L : R;
}
C++ 6 lines easy understand solution.


I rewrite the code in another thread, if p exists, while q does not exist, the result return null.
https://leetcode.com/discuss/46011/dfsversionwhileporqdoesnotexistintreereturnnullptr