Javascript Solution Using Two Recursive Functions


  • 0
    A
    var isBalanced = function(root) {
        var balanced = true;
        var traverse = function(node, depth) {
            var check = function (node, depth, side) {
                if (!node.left && !node.right) {
                    if (side === 'left' && depth > leftHeight) {
                        leftHeight = depth;
                    }
                    if (side === 'right' && depth > rightHeight) {
                        rightHeight = depth;
                    }
                }
                if (node.left) {
                    check(node.left, depth + 1, side);
                }
                if (node.right) {
                    check(node.right, depth + 1, side);
                }
            }
            var leftHeight = 0;
            var rightHeight = 0;
            if (node.left) {
                check(node.left, depth + 1, 'left');
            }
            if (node.right) {
                check(node.right, depth + 1, 'right');
            }
            if (Math.abs(leftHeight - rightHeight) > 1) {
                balanced = false;
            }
            if(node.left) {
                traverse(node.left, 0);
            }
            if (node.right) {
                traverse (node.right, 0)
            }
        }
        if (root) {
            traverse(root, 0);
        }
        return balanced;
    };
    

Log in to reply
 

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