Javascript solution using recursion


  • 0
    S
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {boolean}
     */
    var isBalanced = function(root) {
        return helper(root) !== -1;
    };
    
    var helper =  function(root) {
        if (!root) { return 0; }
        
        var left = helper(root.left);
        var right = helper(root.right);
        if (left === -1 || right === -1 || Math.abs(left - right) > 1) { return -1; }
        return 1 + Math.max(left, right);
    };
    

Log in to reply
 

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