public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode A, TreeNode B) {
if (root == null)
return null;
if (check(root, A)&&check(root,B)){
return lowestCommonAncestor(root,A,B);
}
else {
return null;
}
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
if (root == null || root == A || root == B) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, A, B);
TreeNode right = lowestCommonAncestor(root.right, A, B);
if (left != null && right != null) {
return root;
}
return left == null ? right : left;
}
public boolean check(TreeNode root, TreeNode node){
if (root.left != null && check(root.left, node)) {
return true;
}
if (root.right != null && check(root.right, node)){
return true;
}
if (root == node) {
return true;
}
return false;
}