Skip to content

Instantly share code, notes, and snippets.

@alexhawkins
Created February 18, 2015 05:01
Show Gist options
  • Save alexhawkins/7d48613579f27a7aae7b to your computer and use it in GitHub Desktop.
Save alexhawkins/7d48613579f27a7aae7b to your computer and use it in GitHub Desktop.
Balancing A Binary Tree
/* Write a funciton to check to see if a binary Tree is balanced.
For the purposes of this tree, a balanced tree is defined to be a
tree such that the heights of the subtrees of any node never differ
by more than one */
BinaryTree.prototype.isBalanced = function() {
var checkHeight = function(current) {
if (!current) return 0 //height = 0;
//check to see if left side is balanced
var leftHeight = checkHeight(current.left);
if (leftHeight === -1) return -1;
//check to see if right side is balanced
var rightHeight = checkHeight(current.right);
if (rightHeight === -1) return -1;
//check if current node is balanced
var heightDiff = Math.abs(leftHeight - rightHeight);
if (heightDiff > 1)
return -1 // not balanced
else
return Math.max(leftHeight, rightHeight) + 1;
};
return checkHeight(this.root) === -1 ? false : true;
};
//TESTS
var bt = new BinaryTree();
bt.add(10, 14, 6, 11, 18, 5, 8, 21, 7, 19);
console.log(bt);
console.log('BALANCED: ', bt.isBalanced()) //BALANCED: false;
BinaryTree.prototype.getHeight = function() {
var recurse = function(current) {
if (!current) return 0;
var leftHeight = recurse(current.left) + 1;
var rightHeight = recurse(current.right) + 1;
return Math.max(leftHeight, rightHeight);
};
return recurse(this.root);
};
var height = bt.getHeight();
console.log(height); // 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment