Shouldn't result be false if input is null?


  • 1

    Even i got it passed, the testcase still looks a bit strange to me
    When the input is null, technically speaking, it is not even a tree, shouldn't the result be false?

    Input:	{}
    Output:	false
    Expected:	true
    

    Here is the accepted code in javascript

    /**
     * Memo: Kinda werid to see the result is true when root is null.
     * Runtime: 161ms
     * Rank: S
     */
    var isBalanced = function(root) {
        if (!root) {
            return true; // doesn't look so right  here.
        }
    
        var left = isBalanced(root.left);
        var right = isBalanced(root.right);
    
        if (left && right) {
            var dLeft = getDepth(root.left);
            var dRight = getDepth(root.right);
            return Math.abs(dLeft - dRight) <= 1;
        } else {
            return false;
        }
    };
    
    
    
    var getDepth = function(root) {
        if (!root) {
            return 0;
        }
    
        return Math.max(getDepth(root.left), getDepth(root.right)) + 1;
    };

Log in to reply
 

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