Javascript backtracking


#1
//Definition for a  binary tree node
    // function TreeNode(data){
    //  this.data = data
    //  this.left = null
    //  this.right = null
    // }

module.exports = { 
 //param A : root node of tree
 //param B : integer
 //param C : integer
 //return an integer
    lca : function(A, B, C) {
        var ans = this.traverse(A, B, C);
        var lca = ans[1];
        return lca;
    },
    traverse : function (N, A, B) {
            if(N == null){
                return [false, -1];
            }
            var lAns = this.traverse(N.left, A, B);
            var rAns = this.traverse(N.right, A, B);
            var left = lAns[0], lNode = lAns[1];
            var right = rAns[0], rNode = rAns[1];
            var current = N.data == A || N.data == B;
            var lca = -1;
            if(left){
                lca = lNode;
            }
            if(right){
                lca = rNode; 
            }
            if(left && right || ((left || right) && current) || 
                (current && A == B)) {
                lca = N.data;
            }
        
            return [current || left || right, lca];
    }
    
};