Java Recursive Solution, Beats 79%


  • 0
    S
    TreeNode result;
    
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        result = null;
        check(root, p, q);
        return result;
    }
    
    private boolean check(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return false;
        
        boolean checkLeft = check(root.left, p, q);
        boolean checkRight = check(root.right, p, q);
        
        if (checkLeft && checkRight || ((checkLeft || checkRight) && (root == p || root == q)) ) {
            result = root;
            return false;
        }
        
        if ( (root == p || root == q) || ( checkLeft || checkRight  ) ) return true;
        
        return false;
     
    }
    

    }


  • 0
    X

    Suppose we are given a tree [1,2,3,4,5,6,7,6,7], with root.val==1, p.val==6, q.val==7, will the return has val==3? I tried your program and it seems so. But I'm expecting to get 4.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.