O(N^2) solution is also accepted


#1

O(n^2) recursive solution is also being accepted. This should not happen.
Here’s the code which was accepted:

int lca(TreeNode T, int v, int w) {
if (T == null) {
  return -1;
}
if (T.val == v && T.val == w) {
  return T.val;
}
if (T.val == v) {
  if (findElement(T.left, w) || findElement(T.right, w)) {
    return T.val;
  }
} else if (T.val == w) {
  if (findElement(T.left, v) || findElement(T.right, v)) {
    return T.val;
  }
} else {
  boolean lv = findElement(T.left, v);
  boolean lw = findElement(T.left, w);
  if (lv && lw) {
    return lca(T.left, v, w);
  }
  if (!lv && !lw) {
    return lca(T.right, v, w);
  }
  if (lv) {
    boolean rw = findElement(T.right, w);
    if (rw) {
      return T.val;
    } else {
      return -1;
    }
  } else if (lw) {
    boolean rv = findElement(T.right, v);
    if (rv) {
      return T.val;
    } else {
      return -1;
    }
  }
}
return -1;

}