isBalanced tree with JavaScript


  • 0
    N
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {boolean}
     */
    
    const depth = (root) => {
        if(!root) {
            return 0;
        }
    
        return (root) ? Math.max(depth(root.left), depth(root.right)) + 1 : 0;
    };
    
    const isBalanced = function(root) {
        if(!root) {
            return true;
        }
        
        let delta = Math.abs(depth(root.left) - depth(root.right));
        return (delta > 1) ? false : isBalanced(root.left) && isBalanced(root.right);
    };
    

Log in to reply
 

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