Javascript BFS solution


  • 0
    E
    var isBalanced = function(root) {
        var isbal = true;
        getHeight(root);
        var last = [];
        var children = [root];
        while(1){
            last = children.concat();
            children = [];
            last.forEach((val)=>{
                if(val){
                    var leftHeight = val.left?val.left.height: 0;
                    var rightHeight = val.right?val.right.height: 0;
                    if(Math.abs(leftHeight - rightHeight) > 1) isbal = false;
                    if(val.left) children.push(val.left);
                    if(val.right) children.push(val.right);
                }
            });
            if(!isbal) return false;
            if(children.length === 0) break;
        }
        return true;
    };
    
    var getHeight = (node) => {
        if(!node) return 0;
        node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;
        return node.height;
    };
    

Log in to reply
 

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