Least Common Ancestor

Find the lowest common ancestor in an unordered binary tree given two values in the tree.

Lowest common ancestor : the lowest common ancestor (LCA) of two nodes v and w in a tree or directed acyclic graph (DAG) is the lowest (i.e. deepest) node that has both v and w as descendants. 
Example :

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2_     0        8
         /   \
         7    4

For the above tree, the LCA of nodes 5 and 1 is 3.

LCA = Lowest common ancestor 
Please note that LCA for nodes 5 and 4 is 5.


Solution:

Time: O(n)
Space: O(h)

/**
 * Definition for binary tree
 * class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) {
 *      val = x;
 *      left=null;
 *      right=null;
 *     }
 * }
 */
public class Solution {
    public int lca(TreeNode A, int B, int C) {
        boolean[] found = new boolean[2];
        TreeNode lca = helper(A, B, C, found);
        if (found[0] && found[1]) {
            return lca.val;
        }
        return -1;
    }
    
    private TreeNode helper(TreeNode A, int B, int C, boolean[] found) {
        if (A == null) return null;
        boolean f = false;
        if (A.val == B || A.val == C) {
            f = true;
            if (A.val == B) found[0] = true;
            if (A.val == C) found[1] = true;
        }
        TreeNode left = helper(A.left, B, C, found);
        TreeNode right = helper(A.right, B, C, found);
        if (left != null && right != null) {
            return A;
        }
        if (f) return A;
        if (left != null) return left;
        if (right != null) return right;
        return null;
    }
}