class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

if(root == null || p == null || q == null) return null; if(root == p) return p; if(root == q) return q; boolean pIsRigth = checkChildren(root.right, p); boolean qIsLeft = checkChildren(root.left, q); if((pIsRigth && qIsLeft) || (!pIsRigth && !qIsLeft)) return root; else { if(pIsRigth && !qIsLeft) return lowestCommonAncestor(root.right, p, q); else return lowestCommonAncestor(root.left, p, q); } } public boolean checkChildren(TreeNode root, TreeNode n) { if(root == null) return false; if(root == n) return true; return checkChildren(root.left, n) || checkChildren(root.right, n); }

}