classSolution{TreeNode res;publicTreeNodelowestCommonAncestor(TreeNode root,TreeNode p,TreeNode q){
res =null;find(root, p, q);return res;}privateintfind(TreeNode node,TreeNode p,TreeNode q){if(node ==null)return0;int left =find(node.left, p, q);int right =find(node.right, p, q);// Self could be ancestor as wellint self =0;if(node == p || node == q)++self;// Add the count from left right and self nodesint count = left + right + self;// When found the LCAif(count ==2&& res ==null) res = node;return count;}}