javascript solution


  • 0
    J
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number}
     */
    var largestBSTSubtree = function(root) {
        var res = help(root);
        return res[1];
    };
    function help(root){
        res =[];
        res.push(true);
        res.push(0);//max num
        res.push(0);//totoal num
        res.push(Infinity);//min
        res.push(-Infinity);//max
        if(root===null) {
            return res;
        }
    
        var s1 = help(root.left);
        var s2 = help(root.right);
    
         if(s1[0] && s2[0] && root.val<s2[3] && root.val > s1[4]){//BST;
             res[0]= true;
            res[1]=  s1[1]+s2[1] +1;
      
        }else{
              res[0]= false;
            res[1]= Math.max(s1[1],s2[1]);
    
        }
            res[2] = s1[2] + s2[2] +1;
            res[3] = Math.min(root.val, Math.min(s1[3],s2[3]));
            res[4] = Math.max(root.val, Math.max(s1[4],s2[4]));
        return res;
      
    }```

Log in to reply
 

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