This code is only valid if A and B exist in the tree
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
if (root == null) {
return null;
}
if (root == A || root == B) {
return root;
}
TreeNode isLeft = lowestCommonAncestor(root.left, A, B);
TreeNode isRight = lowestCommonAncestor(root.right, A, B);
if (isLeft != null && isRight != null) {
return root;
} else {
return isLeft == null ? isRight : isLeft;
}
}