Skip to content

Instantly share code, notes, and snippets.

@tomgullo
Last active December 21, 2015 22:49
Show Gist options
  • Save tomgullo/6378067 to your computer and use it in GitHub Desktop.
Save tomgullo/6378067 to your computer and use it in GitHub Desktop.
is_balanced
log = console.log
function node(name, parent, child) {
var new_node = { name:name, parent:parent }
if (!!child) {
new_node.parent[child] = new_node;
}
return new_node
}
/*
root
rl rr
rl2 rr2
rl3 rr3
*/
root = node('root')
rl = node('rl', root, 'left')
rl2 = node('rl2', rl, 'left')
rl3 = node('rl3', rl2, 'left')
rr = node('rr', root, 'right')
rr2 = node('rr2', rr, 'right')
rr3 = node('rr3', rr2, 'right')
rlr = node('rlr', rl, 'right') //balances tree
rrl = node('rrl', rr, 'left') //balances tree
function height(nodz) {
return (!nodz) ? 0 : 1 + Math.max(height(nodz.left), height(nodz.right));
}
function isBalanced(nodz) {
return ((!nodz) || isBalanced(nodz.left) && isBalanced(nodz.right) && Math.abs(height(nodz.left) - height(nodz.right)) <= 1)
}
//log(height(root))
log("is balanced? " + isBalanced(root));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment